POJ 3259 Wormholes BellmanFord算法,判断负圈

#include 
using namespace std;
struct Edge
{
    int from, to, cost;
    Edge(int from = 0, int to = 0, int cost = 0) : from(from), to(to), cost(cost) {}
};
Edge edges[6000];
int N, M, W, inf = 0x3f3f3f3f, d[507];
void input()
{
    scanf("%d%d%d", &N, &M, &W);
    int from, to, cost;
    for (int i = 1; i <= M; i++)
    {
        scanf("%d%d%d", &from, &to, &cost);
        edges[i] = Edge(from, to, cost);
        edges[i + M] = Edge(to, from, cost);
    }
    for (int i = 1; i <= W; i++)
    {
        scanf("%d%d%d", &from, &to, &cost);
        edges[M * 2 + i] = Edge(from, to, -cost);
    }
}
bool bellmanFord(int s)
{
    for (int i = 1; i <= N; i++)
    {
        d[i] = inf;
    }
    d[s] = 0;
    bool nagativeLoop = false;
    for (int i = 0; i <= N; i++)
    {
        for (int j = 1; j <= (M * 2 + W); j++)
        {
            if (edges[j].cost + d[edges[j].from] < d[edges[j].to])
            {
                d[edges[j].to] = edges[j].cost + d[edges[j].from];
                if (i >= N)
                {
                    nagativeLoop = true;
                }
            }
        }
    }
    return nagativeLoop;
}
void solve()
{
    bool flag = bellmanFord(1);
    if (flag)
    {
        printf("YES\n");
    }
    else
    {
        printf("NO\n");
    }
}
int main()
{
    int F;
    scanf("%d", &F);
    while (F--)
    {
        input();
        solve();
    }
    return 0;
}

你可能感兴趣的:(算法,图论)