Wormholes (POJ 3259)(判断负圈)(spfa) 最短路专题
题目描述
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.
题目大意:两个点之间有两种路径,一种是花费时间,一种是增加时间的,问你是否存在环,使得在走过这个环后耗费时间小于等于0。
思路:很明显的判断负环,需要注意的是花费时间的是双向,而增加时间的是单向道路。还有就是会有重边存在,需要在读入是做一点处理。最后跑一遍spfa即可。
代码:
#include<bits/stdc++.h>
#define ll long long
#define MOD 998244353
#define INF 0x3f3f3f3f
#define mem(a,x) memset(a,x,sizeof(a))
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
const int NUM=505;
struct edge{
int from,to,w;
edge(int a,int b,int c){from=a;to=b;w=c;}
};
int n,m1,m2;
int mp[505][505];
vector<edge>e[NUM];
void init()
{
for(int i=1;i<=n;i++){
e[i].clear();
}
}
bool spfa()
{
int dis[NUM];
bool inq[NUM];
int neg[NUM];
for(int i=1;i<=n;i++){dis[i]=INF;inq[i]=false;neg[i]=0;}
dis[1]=0;
neg[1]++;
queue<int>Q;
Q.push(1);
inq[1]=1;
while(!Q.empty())
{
int u=Q.front();
Q.pop();
inq[u]=0;
for(int i=0;i<e[u].size();i++){
int v=e[u][i].to;
int w=e[u][i].w;
if(dis[v]>dis[u]+w){
dis[v]=dis[u]+w;
if(!inq[v]){
Q.push(v);
inq[v]=1;
neg[v]++;
if(neg[v]>=n)return 1;
}
}
}
}
return 0;
}
int main()
{
int t;
cin>>t;
while(t--){
cin>>n>>m1>>m2;
mem(mp,0);
init();
for(int i=1;i<=m1;i++){
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
if(mp[a][b]==0){
mp[a][b]=c;
mp[b][a]=c;
}else{
mp[a][b]=min(mp[a][b],c);
mp[b][a]=mp[a][b];
}
e[a].push_back(edge(a,b,mp[a][b]));
e[b].push_back(edge(b,a,mp[a][b]));
}
for(int i=1;i<=m2;i++){
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
if(mp[a][b]==0){
mp[a][b]=-c;
}else{
mp[a][b]=min(mp[a][b],-c);
}
e[a].push_back(edge(a,b,mp[a][b]));
}
if(spfa()){
cout<<"YES"<<endl;
}else{
cout<<"NO"<<endl;
}
}
return 0;
}