poj 3259 Wormholes

来源:互联网 发布:伊朗 知乎 编辑:程序博客网 时间:2024/06/13 05:36

Language: Wormholes Time Limit: 2000MS Memory Limit: 65536K Total
Submissions: 44261 Accepted: 16285 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.

Input

Line 1: A single integer, F. F farm descriptions follow. Line 1 of
each farm: Three space-separated integers respectively: N, M, and W
Lines 2..M+1 of each farm: Three space-separated numbers (S, E, T)
that describe, respectively: a bidirectional path between S and E that
requires T seconds to traverse. Two fields might be connected by more
than one path. Lines M+2..M+W+1 of each farm: Three space-separated
numbers (S, E, T) that describe, respectively: A one way path from S
to E that also moves the traveler back T seconds. Output

Lines 1..F: For each farm, output “YES” if FJ can achieve his goal,
otherwise output “NO” (do not include the quotes).

dfs版spfa判负环。

#include<cstdio>#include<cstring>int fir[510],ne[6010],to[6010],len[6010],m,n,w,dis[510],cnt[510];void add(int num,int f,int t,int l){    ne[num]=fir[f];    fir[f]=num;    to[num]=t;    len[num]=l;}bool dfs(int u){    int i,v;    cnt[u]++;    if (cnt[u]>n+1) return 1;    for (i=fir[u];i;i=ne[i])    {        v=to[i];        if (dis[u]+len[i]<dis[v])        {            dis[v]=dis[u]+len[i];            if (dfs(v)) return 1;        }    }    return 0;}int main(){    int T,i,j,k,x,y,z;    bool flag;    scanf("%d",&T);    while (T--)    {        memset(fir,0,sizeof(fir));        memset(ne,0,sizeof(ne));        memset(dis,0,sizeof(dis));        memset(cnt,0,sizeof(cnt));        scanf("%d%d%d",&n,&m,&w);        for (i=1;i<=m;i++)        {            scanf("%d%d%d",&x,&y,&z);            add(i*2,x,y,z);            add(i*2+1,y,x,z);        }        for (i=1;i<=w;i++)        {            scanf("%d%d%d",&x,&y,&z);            add(i+m*2+1,x,y,-z);        }        flag=0;        for (i=1;i<=n;i++)          if (dfs(i))          {            flag=1;            break;          }        if (flag) printf("YES\n");        else printf("NO\n");    }}
0 0
原创粉丝点击