poj3259 bellman判正環

繼續bellman判正環

注意path是雙向的,蟲洞是單向的

d[510]爲各點與源點距離,然而沒有源點。。。各點之間初始一樣就可以

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <queue>
#include <cstring>
#include <math.h>
#include <map>
#define FOR(i,j,k) for(int i=j;i<=k;i++)
using namespace std;
const int inf=10001;
int n;
int tot;
struct node{
    int x,y,t;
}edge[5210];
int d[510];
bool bellman()
{
    for(int i=1;i<=n;i++)
        d[i]=inf;         //確保每個點到源點距離一樣就可以,d[i]=0也可以
    bool flag;
    for(int i=1;i<=n-1;i++)
    {
        flag=false;
        for(int j=1;j<=tot;j++)
            if(d[edge[j].y]>d[edge[j].x]+edge[j].t)
            {
                d[edge[j].y]=d[edge[j].x]+edge[j].t,flag=true;
                //printf("%d ",d[edge[j].y]);
            }
        if(flag==false)
            break;
    }

    for(int j=1;j<=tot;j++)
        if(d[edge[j].y]>d[edge[j].x]+edge[j].t)
            return true;
    return false;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int m,w;
        tot=0;
        scanf("%d%d%d",&n,&m,&w);
        int s,e,temp;
        for(int i=1;i<=m;i++){
            scanf("%d%d%d",&s,&e,&temp);
            tot++;
            edge[tot].x=s,edge[tot].y=e,edge[tot].t=temp;
            tot++;
            edge[tot].x=e,edge[tot].y=s,edge[tot].t=temp;
        }
        for(int i=m+1;i<=w+m;i++)
        {
            scanf("%d%d%d",&s,&e,&temp);
            tot++;
            edge[tot].x=s,edge[tot].y=e,edge[tot].t=-temp;
        }
        if(bellman())
            cout<<"YES"<<endl;
        else cout<<"NO"<<endl;
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章