1. 程式人生 > >[BZOJ1715][Usaco2006 Dec]Wormholes 蟲洞

[BZOJ1715][Usaco2006 Dec]Wormholes 蟲洞

com return 否則 true 輸出 include nes each 進入

1715: [Usaco2006 Dec]Wormholes 蟲洞

Time Limit: 5 Sec Memory Limit: 64 MB Submit: 902 Solved: 475 [Submit][Status][Discuss]

Description

John在他的農場中閑逛時發現了許多蟲洞。蟲洞可以看作一條十分奇特的有向邊,並可以使你返回到過去的一個時刻(相對你進入蟲洞之前)。John的每個農場有M條小路(無向邊)連接著N (從1..N標號)塊地,並有W個蟲洞。其中1<=N<=500,1<=M<=2500,1<=W<=200。 現在John想借助這些蟲洞來回到過去(出發時刻之前),請你告訴他能辦到嗎。 John將向你提供F(1<=F<=5)個農場的地圖。沒有小路會耗費你超過10000秒的時間,當然也沒有蟲洞回幫你回到超過10000秒以前。

Input

* Line 1: 一個整數 F, 表示農場個數。

* Line 1 of each farm: 三個整數 N, M, W。

* Lines 2..M+1 of each farm: 三個數(S, E, T)。表示在標號為S的地與標號為E的地中間有一條用時T秒的小路。

* Lines M+2..M+W+1 of each farm: 三個數(S, E, T)。表示在標號為S的地與標號為E的地中間有一條可以使John到達T秒前的蟲洞。

Output

* Lines 1..F: 如果John能在這個農場實現他的目標,輸出"YES",否則輸出"NO"。

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 <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
char buf[10000000], *ptr = buf - 1;
inline int readint(){
    int f = 1, n = 0;
    char ch = *++ptr;
    while(ch < 0 || ch > 
9){ if(ch == -) f = -1; ch = *++ptr; } while(ch <= 9 && ch >= 0){ n = (n << 1) + (n << 3) + ch - 0; ch = *++ptr; } return f * n; } const int maxn = 500 + 10, maxm = 3000 + 10; struct Edge{ int to, val, next; Edge(){} Edge(int _t, int _v, int _n): to(_t), val(_v), next(_n){} }e[maxm * 2]; int fir[maxn], cnt; inline void add(int u, int v, int w){ e[++cnt] = Edge(v, w, fir[u]); fir[u] = cnt; } int dis[maxn]; bool flag, vis[maxn] = {false}; void spfa(int u){ if(flag) return; vis[u] = true; for(int v, i = fir[u]; i; i = e[i].next){ v = e[i].to; if(dis[v] > dis[u] + e[i].val){ if(vis[v]){ flag = true; break; } dis[v] = dis[u] + e[i].val; spfa(v); } } vis[u] = false; } int main(){ fread(buf, sizeof(char), sizeof(buf), stdin); int T = readint(); while(T--){ int n, m, w; n = readint(); m = readint(); w = readint(); cnt = 0; for(int i = 1; i <= n; i++) fir[i] = 0; for(int s, e, t, i = 1; i <= m; i++){ s = readint(); e = readint(); t = readint(); add(s, e, t); add(e, s, t); } for(int s, e, t, i = 1; i <= w; i++){ s = readint(); e = readint(); t = readint(); add(s, e, -t); } flag = false; for(int i = 1; i <= n; i++) dis[i] = 0; for(int i = 1; i <= n && !flag; i++) spfa(i); puts(flag ? "YES" : "NO"); } return 0; }

[BZOJ1715][Usaco2006 Dec]Wormholes 蟲洞