POJ 3259 Wormholes(Bellman-Ford判负环)

Description
判断一个图中是否存在负环
Input
第一行为用例组数t,每组用例第一行为三个整数n,m,w分别表示顶点数,双向边个数,单向边个数,之后m行每行三个整数a,b,d表示a和之间有一条权值为d的双向边,最后w行每行三个整数a,b,d表示a和b之间有一条权值为-d的单向边
Output
若图中存在负环则输出YES,否则输出NO
Sample Input
2
3 3 1
1 2 2
1 3 4
2 3 1
3 1 3
3 2 1
1 2 3
2 3 4
3 1 8
Sample Output
NO
YES
Solution
Bellman-Ford
Code

#include<cstdio>
#include<iostream>
using namespace std;
#define INF (1<<29)
#define maxm 2710
#define maxv 505
struct node
{
    int x,y,t;
}edge[maxm];
int T,n,m,w;
int Bellman_Ford()
{
    int i,j,d[maxv],res=1;
    for(i=1;i<=n;i++)//初始化 
        d[i]=INF;
    int flag=1;
    while(flag)
    {
        flag=0;
        if(res++>n)
            return 1;
        for(i=1;i<=m;i++)//双向边 
        {
            if(d[edge[i].x]>d[edge[i].y]+edge[i].t)
            {
                d[edge[i].x]=d[edge[i].y]+edge[i].t;
                flag=1;
            }
            if(d[edge[i].y]>d[edge[i].x]+edge[i].t)
            {
                d[edge[i].y]=d[edge[i].x]+edge[i].t;
                flag=1;
            }
        }
        for(;i<=m+w;i++)//单向边 
            if(d[edge[i].y]>d[edge[i].x]-edge[i].t)
            {
                d[edge[i].y]=d[edge[i].x]-edge[i].t;
                flag=1;
            }
    }
    return 0;
}
int main()
{
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d%d",&n,&m,&w);
        for(int i=1;i<=m+w;i++)
            scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].t);
        if(Bellman_Ford())//存在负环 
            printf("YES\n");
        else//不存在负环 
            printf("NO\n");
    }
    return 0;
}

你可能感兴趣的:(POJ 3259 Wormholes(Bellman-Ford判负环))