poj 3259 Wormholes(spfa 判环)

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
#define INF 100000000
int u[6000],v[6000],w[6000];
int first[6000],next[6000];
int coun[6000];
__int64 d[6000];
int main()
{
    int f,n,m,ww,s,e,t;
    int i,j,k;
    scanf("%d",&f);
    while(f--)
    {
        scanf("%d%d%d",&n,&m,&ww);
        memset(first,-1,sizeof(first));
        memset(coun,0,sizeof(coun));
        int ok=0;
        for(i=1;i<=2*m;i+=2)
        {
            scanf("%d%d%d",&s,&e,&t);
            u[i]=s;  v[i]=e;  w[i]=t;
            u[i+1]=e;v[i+1]=s;w[i+1]=t;

            next[i]=first[u[i]];
            first[u[i]]=i;
            next[i+1]=first[u[i+1]];
            first[u[i+1]]=i+1;
        }
        for(i=2*m+1;i<=2*m+ww;i++)
        {
            scanf("%d%d%d",&s,&e,&t);
            u[i]=s;v[i]=e;w[i]=-t;

            next[i]=first[u[i]];
            first[u[i]]=i;
        }

        //queue<int> q;
        int tot[6000];
        int cnt=0;
        bool inq[6000];
        for(i=0;i<=n;i++) d[i]=INF;
        d[1]=0;
        memset(inq,0,sizeof(inq));
        //q.push(1);
        tot[cnt++]=1;
        coun[1]++;
        //while(!q.empty())
        while(cnt)
        {
            if(ok==1) break;
            //int x=q.front();q.pop();
            int x=tot[--cnt];
            inq[x]=false;
            for(int e=first[x];e!=-1;e=next[e])
            {
                if(d[v[e]]>d[x]+w[e])
                {
                    d[v[e]]=d[x]+w[e];
                    if(!inq[v[e]])
                    {
                        inq[v[e]]=true;
                        //q.push(v[e]);
                        tot[cnt++]=v[e];
                        coun[v[e]]++;
                        if(coun[v[e]]>n) {ok=1;break;}
                    }
                }
            }
        }
        if(ok==1) printf("YES\n");
        else printf("NO\n");
    }

    return 0;
}
View Code

 

posted @ 2015-01-25 01:24  sola94  阅读(104)  评论(0编辑  收藏  举报