UVa:558 Wormholes

Bellman-ford判断是否存在负权值回路。

 

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
struct Edge
{
    int to,from,cost;
};
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int n,m;
        scanf("%d%d",&n,&m);
        Edge e[2005];
        for(int i=0; i<m; ++i)
            scanf("%d%d%d",&e[i].to,&e[i].from,&e[i].cost);
        int d[1005],ok=false;
        memset(d,0,sizeof(d));
        for(int i=0; i<n; ++i)
        {
            for(int j=0; j<m; ++j)
            {
                if(d[e[j].from]>d[e[j].to]+e[j].cost)
                {
                    d[e[j].from]=d[e[j].to]+e[j].cost;
                    if(i==n-1)
                    {
                        ok=true;
                        break;
                    }
                }
            }
        }
            if(ok) puts("possible");
            else puts("not possible");
        }
        return 0;
    }


 

你可能感兴趣的:(Bellman-Ford,单源最短路)