(简单) POJ 3259 Wormholes,SPFA判断负环。

  Description

  While exploring his many farms, Farmer John has discovered a number of amazing wormholes. A wormhole is very peculiar because it is a one-way path that delivers you to its destination at a time that is BEFORE you entered the wormhole! Each of FJ's farms comprises N (1 ≤ N ≤ 500) fields conveniently numbered 1..N, M (1 ≤ M ≤ 2500) paths, and W (1 ≤ W ≤ 200) wormholes.

  As FJ is an avid time-traveling fan, he wants to do the following: start at some field, travel through some paths and wormholes, and return to the starting field a time before his initial departure. Perhaps he will be able to meet himself :) .

  To help FJ find out whether this is possible or not, he will supply you with complete maps to F (1 ≤ F ≤ 5) of his farms. No paths will take longer than 10,000 seconds to travel and no wormhole can bring FJ back in time by more than 10,000 seconds.

 

  就是求是否存在负环,这样的话一定能够时间倒退。。。

 

代码如下:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>

using namespace std;

const int INF=10e8;
const int MaxN=510;

struct Edge
{
    int v,cost;

    Edge(int _v,int _cost):v(_v),cost(_cost) {}
};

vector <Edge> E[MaxN];
bool vis[MaxN];
int couNode[MaxN];

bool SPFA(int lowcost[],int n,int start)
{
    queue <int> que;
    int u,v,c;
    int len;

    for(int i=1;i<=n;++i)
    {
        lowcost[i]=INF;
        vis[i]=0;
        couNode[i]=0;
    }
    vis[start]=1;
    couNode[start]=1;
    lowcost[start]=0;

    que.push(start);

    while(!que.empty())
    {
        u=que.front();
        que.pop();

        vis[u]=0;
        len=E[u].size();

        for(int i=0;i<len;++i)
        {
            v=E[u][i].v;
            c=E[u][i].cost;

            if(lowcost[u]+c<lowcost[v])
            {
                lowcost[v]=lowcost[u]+c;

                if(!vis[v])
                {
                    vis[v]=1;
                    ++couNode[v];
                    que.push(v);

                    if(couNode[v]>=n)
                        return 0;
                }
            }
        }
    }

    return 1;
}

inline void addEdge(int u,int v,int c)
{
    E[u].push_back(Edge(v,c));
}

int ans[MaxN];

int main()
{
    int T;
    int N,M,W;
    int a,b,c;

    scanf("%d",&T);

    while(T--)
    {
        scanf("%d %d %d",&N,&M,&W);

        for(int i=1;i<=N;++i)
            E[i].clear();

        for(int i=1;i<=M;++i)
        {
            scanf("%d %d %d",&a,&b,&c);

            addEdge(a,b,c);
            addEdge(b,a,c);
        }

        for(int i=1;i<=W;++i)
        {
            scanf("%d %d %d",&a,&b,&c);

            addEdge(a,b,-c);
        }

        if(SPFA(ans,N,1))
            printf("NO\n");
        else
            printf("YES\n");
    }

    return 0;
}
View Code

 

posted @ 2015-03-14 23:24  WhyWhy。  阅读(135)  评论(0编辑  收藏  举报