http://poj.org/problem?id=3259
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 37356 | Accepted: 13734 |
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 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
Sample Input
2 3 3 1 1 2 2 1 3 4 2 3 1 3 1 3 3 2 1 1 2 3 2 3 4 3 1 8
Sample Output
NO YES
代码:
#include <iostream> #include <cmath> #include <cstring> #include <cstdlib> #include <cstdio> #include <algorithm> #include <vector> #include <queue> #include <stack> using namespace std; const int INF = (1<<30)-1; #define min(a,b) (a<b?a:b) #define max(a,b) (a>b?a:b) #define N 5500 int n, m, w, dist[N], G[N][N], vis[N]; int u; struct node { int v, t, next; } a[N]; int Head[N], cnt; void Init() { cnt = 0; memset(Head, -1, sizeof(Head)); memset(vis, 0, sizeof(vis)); for(int i=0; i<=n; i++) { dist[i] = INF; for(int j=0; j<=i; j++) G[i][j] = G[j][i] = INF; } } void Add(int u, int v, int t) { a[cnt].v = v; a[cnt].t = t; a[cnt].next = Head[u]; Head[u] = cnt++; } int spfa() { queue<int>Q; Q.push(1); dist[1] = 0; vis[1] = 1; while(Q.size()) { int u = Q.front(); Q.pop(); vis[u] = 0; for(int i=Head[u]; i!=-1; i=a[i].next) { int v = a[i].v; int t = a[i].t; if(dist[u] + t < dist[v]) { dist[v] = dist[u] + t; if(vis[v] == 0) { Q.push(v); vis[v] = 1; } } } if(dist[1] < 0) ///当 dist[1] 为负数的时候说明它又回到了原点 return 1; } return 0; } int main() { int t; scanf("%d", &t); while(t--) { int i, u, v, x; scanf("%d%d%d", &n, &m, &w); Init(); for(i=1; i<=m; i++) { scanf("%d%d%d", &u, &v, &x); Add(u, v, x); Add(v, u, x); } for(i=1; i<=w; i++) { scanf("%d%d%d", &u, &v, &x); Add(u, v, -x); } int ans = spfa(); if(ans) printf("YES\n"); else printf("NO\n"); } return 0; }