题目地址
http://poj.org/problem?id=3259
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 37361 | Accepted: 13736 |
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
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这题主要是把题读懂。题意是:
2个test case 每个test case 第一行:
N M W
N个点 M条双向正权边 W条单向负权边 第一个test case 最后一行 3 1 3 是单向负权边,3->1的边权值是-3
因为有负边,所以用bellman-ford算法就行。
AC代码:
#include <stdio.h> #include <string.h> #define N 505 #define inf 100000 int d[N]; int n, m; typedef struct { int from; int to; int cost; }node; node edges[5300]; int bellman_ford(int m) { int i, j, k, t; int ok; for(i=1; i<=n; i++) d[i] = inf; d[1] = 0; for(i=1; i<=n-1; i++) { ok = 1; for(j=1; j<=m; j++) { if(d[edges[j].from] > d[edges[j].to] + edges[j].cost) { d[edges[j].from] = d[edges[j].to] + edges[j].cost; ok = 0; } } if(ok) break; } for(j=1; j<=m; j++) { if(d[edges[j].from] > d[edges[j].to] + edges[j].cost) return 0; } return 1; } int main() { int i, j, t, x; int a, b, c, w; scanf("%d", &t); while(t--) { scanf("%d%d%d", &n, &m, &w); memset(edges, 0, sizeof(edges)); for(i=0, j=1; j<=m;j++) { scanf("%d%d%d", &a, &b, &c); i++; edges[i].from = a; edges[i].to= b; edges[i].cost = c; i++; edges[i].from = b; edges[i].to = a; edges[i].cost = c; } for(j=1; j<=w; j++) { scanf("%d%d%d", &a, &b, &c); i++; edges[i].from = a ; edges[i].to = b; edges[i].cost = -c; } if(bellman_ford(i)) printf("NO\n"); else printf("YES\n"); } return 0; }