Wormholes Time Limit:2000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
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
23 3 11 2 21 3 42 3 13 1 33 2 11 2 32 3 43 1 8
Sample Output
NOYES
Hint
#include#include #include using namespace std;#define N 550#define INF 0xffffffstruct node{ int y, w;}P[N];vector G[N];int v[N];int spfa(int s){ queue Q; Q.push(s); while(Q.size()) { s = Q.front(); Q.pop(); int len = G[s].size(); for(int i = 0; i < len; i++) { node q = G[s][i]; if(v[s] + q.w < v[q.y]) { v[q.y] = v[s] + q.w; Q.push(q.y); } } if(v[1] < 0) return 1; } return 0;}int main(){ int t, n, m, w, s, e, f; cin >> f; while(f--) { for(int i = 1; i < N; i++) { v[i] = INF; G[i].clear(); } v[1] = 0; cin >> n >> m >> w; node p; for(int i = 0; i < m; i++) { cin >> s >> e >> t; p.y = e, p.w = t; G[s].push_back(p); p.y = s; G[e].push_back(p); } for(int i = 0; i < w; i++) { cin >> s >> e >> t; p.y = e, p.w = -t; G[s].push_back(p); } int ans = spfa(1); if(ans) cout << "YES" << endl; else cout << "NO" << endl; } return 0;}
SPFA 在形式上和宽度优先搜索非常类似,不同的是宽度优先搜索中一个点出了队列就不可能重新进入队列,但是SPFA中一个点可能在出队列之后再次被放入队列,也就是一个点改进过其它的点之后,过了一段时间可能本身被改进,于是再次用来改进其它的点,这样反复迭代下去。