标签:
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
Hint
思路:普通路双向,正值;虫洞单向,负值;bellman_ford 判负环;
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#define INF 0x3f3f3f3f
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long LL;
const int N=1002;
int dist[N];
int gra[N][N],vis[N][N];
bool bellman_ford(int n,int s)
{
for(int i=1;i<=n;i++)
{
dist[i]=INF;
}
dist[s]=0;
for(int i=1;i<=n-1;i++)
{
int flag=false;
for(int j=1;j<=n;j++){
for(int k=1;k<=n;k++){
if(vis[j][k]==1&&dist[k]>dist[j]+gra[j][k])
{
dist[k]=dist[j]+gra[j][k];
flag=true;
}
}
}
if(!flag) return false;
}
for(int j=1;j<=n;j++){
for(int k=1;k<=n;k++){
if(vis[j][k]==1&&dist[k]>dist[j]+gra[j][k])
return true;
}
}
return false;
}
int main()
{
int T;scanf("%d",&T);
while(T--)
{
int n,m,w;
scanf("%d%d%d",&n,&m,&w);
mem(vis,0);
int s,e,t;
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&s,&e,&t);
if(vis[s][e])
{
if(gra[s][e]>t)
gra[s][e]=gra[e][s]=t;
}
else{
gra[s][e]=gra[e][s]=t;
vis[s][e]=vis[e][s]=1;
}
}
for(int i=0;i<w;i++)
{
scanf("%d%d%d",&s,&e,&t);
gra[s][e]=0-t;
vis[s][e]=1;
}
int flag=0;
for(int i=1;i<=1;i++) //只用判1,就行了,图是联通的,不然临接矩阵超时!!
{
if(bellman_ford(n,i))
{
flag=1;
break;
}
}
// for(int i=1;i<=n;i++)
// printf("%d___",dist[i]);
// printf("%d\n",gra[3][1]);
if(flag)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
poj 3259 Wormholes[ bellman_ford 判负环]
标签:
原文地址:http://blog.csdn.net/code_or_code/article/details/43792351