2019E0_H 魔法陣

魔法陣

題目

知識點:最短路

克萊恩在一場冒險中得到了得到了一個破損的魔法陣,這個魔法陣是一個有n個點m條邊的有向有環圖,任意兩點之間最多隻有一條邊,每條邊有一個能量值a(可能是負數,別問問就是magical),不存在負環。

克萊恩試圖去修補這個魔法陣。已知,這個魔法陣缺少了3條邊,且已經知道這3條邊的起點和終點(有向)。對於每條邊,克萊恩要賦予其一個能量值c,爲了避免邪神出現,修補過程以及結束後也不能出現負環。

請問每次的最小花費是多少(保證有解,可以是負數)。

輸入

第一行兩個正整數n,m(1≤n≤300,n−1≤m≤500)

接下來m行,每行三個整數x,y,z,表示x->y有一條權值爲z的邊 (0≤x,y<n,−1000≤z≤1000)

最後三行,每行兩個整數u,v表示需要填補一條u->v的邊

輸出

三行,每行一個整數

輸入樣例

10 15
4 7 10
7 6 3
5 3 3
1 4 11
0 6 20
9 8 25
3 0 9
1 2 15
9 0 27
5 2 0
7 3 -5
1 7 21
5 0 1
9 3 16
1 8 4
4 1
0 3
6 9

輸出樣例

-11
-9
-45

思路

水題。

要保證u->v之間添加一條邊之後沒有負環,那麼這個長度最小應該爲-dis[v][u],這樣這個最小環是0。

又因爲有負邊,所以應該要floyd或者bellman ford算法。所以跑三次floyd或者bellman ford求最短路即可。

代碼

#include <cstdio>
#include <utility>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;

typedef long long ll;
const int ms = 500 + 10;
int head[ms], edg[ms], nex[ms]; ll val[ms], d[ms];
int n, m, cnt;

queue<int>q;
bool vis[ms];

void add(int x, int y, ll z)
{
    val[++cnt] = z, edg[cnt] = y, nex[cnt] = head[x], head[x] = cnt;
}

void sfpa(int begin)
{
    memset(d, 0x3f, sizeof(d));
    memset(vis, false, sizeof(vis));
    q.push(begin); d[begin] = 0, vis[begin] = true;
    while (!q.empty())
    {
        int x = q.front(); q.pop();
        vis[x] = false;
        for (int i = head[x]; i; i = nex[i])
        {
            int y = edg[i], z = val[i];
            if (d[y] > d[x] + z)
            {
                d[y] = d[x] + z;
                if (!vis[y]) q.push(y), vis[y] = true;
            }
        }
    }
}

int main()
{
    int t = 1;
    //scanf("%d", &t);
    while (t--)
    {
        cnt = 0;
        memset(nex, 0, sizeof(nex));
        memset(head, 0, sizeof(head));
        scanf("%d%d", &n, &m);
        int x, y; ll z;
        for (int i = 0; i < m; ++i)
        {
            scanf("%d%d%lld", &x, &y, &z);
            x++, y++;
            add(x, y, z);
        }
        for (int i = 0; i < 3; ++i)
        {
            scanf("%d%d", &x, &y);
            x++, y++;
            sfpa(y);
            z = d[x];
            add(x, y, -z);
            printf("%lld\n", -z);
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章