1. 程式人生 > >E - Wormholes (POJ - 3259)

E - Wormholes (POJ - 3259)

ret str edge brush 負環 esp tdi 還要 sin

- 題目大意

個人要穿越到未來,但是之後還要回去,並且回去的時間要在他穿越之前。

- 解題思路

我們可以把在蟲洞中的時間看做是負邊權,然後利用bellman-ford算法來判斷有沒有負環即可。

- 代碼

#include<cstdio>
#include<cstring>
using namespace std;
const int M=1e5;
const int INF=0x3f3f3f;
int d[M],cnt;
struct edge{
   int u,v,w;
}e[M];

bool BellmanFord(int s,int n,int m)
{
    memset(d,INF,sizeof(d));
    d[s]=0;
    bool updated=true;
    int round =0;
    while(updated)
    {
        updated=false;
        round++;
        for(int i=0;i<m;i++)
        {
            int u=e[i].u,v=e[i].v,w=e[i].w;
            if(d[v]>d[u]+w)
               {
                   d[v]=d[u]+w;
                   updated=true;
               }
        }

    if(round>=n&&updated)
        return true;
    }
    return false;
}

int main()
{
    int t,n,m,w,k,s,time;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d%d",&n,&m,&w);
        cnt=0;
        for(int i=0;i<m;i++)
        {
            scanf("%d%d%d",&s,&k,&time);
            e[cnt].u=s;
            e[cnt].v=k;
            e[cnt++].w=time;
            e[cnt].u=k;
            e[cnt].v=s;
            e[cnt++].w=time;
        }
        for(int i=0;i<w;i++)
        {
            scanf("%d%d%d",&s,&k,&time);
            e[cnt].u=s;
            e[cnt].v=k;
            e[cnt++].w=-time;
        }
        if(BellmanFord(1,n,cnt))
            printf("%s\n","YES");
        else
            printf("%s\n","NO");
    }
}

  

E - Wormholes (POJ - 3259)