# Wormholes

##### Total Submission(s) : 81   Accepted Submission(s) : 27

Problem 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 toF (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, <i>F</i>. <i>F</i> farm descriptions follow.<br>Line 1 of each farm: Three space-separated integers respectively: <i>N</i>, <i>M</i>, and <i>W</i><br>Lines 2..<i>M</i>+1 of each farm: Three space-separated numbers (<i>S</i>, <i>E</i>, <i>T</i>) that describe, respectively: a bidirectional path between <i>S</i> and <i>E</i> that requires <i>T</i> seconds to traverse. Two fields might be connected by more than one path.<br>Lines <i>M</i>+2..<i>M</i>+<i>W</i>+1 of each farm: Three space-separated numbers (<i>S</i>, <i>E</i>, <i>T</i>) that describe, respectively: A one way path from <i>S</i> to <i>E</i> that also moves the traveler back <i>T</i> seconds.

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

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

Source PKU

``````#include <iostream>
#include <cstring>
#include <string>
#include <stdio.h>
#define inf 0x3f3f3f3f
using namespace std;
struct paths{
int s,e,t;
}p;
bool flag;
int n,m,w,cnt;
int dis;
int main()
{
int i,j,k,temp;
int t;
cin>>t;
while(t--)
{
cin>>n>>m>>w;
for(i=1;i<=m;i++){
cin>>p[i].s>>p[i].e>>p[i].t;
p[i+m].s=p[i].e;p[i+m].e=p[i].s;p[i+m].t=p[i].t; //输入每点情况
}
k=2*m+w; //注意这是边数。
for(i=2*m+1;i<=k;i++)
{
cin>>p[i].s>>p[i].e>>temp;
p[i].t=-temp;
}
m=k;

for(j=1;j<=n;j++) dis[j]=inf;//初始化
dis=0;
for(j=1;j<=n;j++)
{
flag=0;
for(k=1;k<=m;k++)
{
if(dis[p[k].s]>p[k].t+dis[p[k].e]){

dis[p[k].s]=p[k].t+dis[p[k].e];flag=1;
}
}

if(!flag)break;  //优化
}
flag=0;
for(k=1;  k<=m; k++)  //如果仍有大于它的则出现负环
{
if(dis[p[k].s]>p[k].t+dis[p[k].e]){flag=1;break;}
}
if(flag)cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}
``````

原文作者：Bellman - ford算法
原文地址: https://blog.csdn.net/sinat_37668729/article/details/76977921
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。 