题目:POJ 3259
Description:
F组数据, 输入n, m, w,表示n块田地, m个田与田之间的关系,w个虫洞,从一块田到达另一块田需要花一定时间, 穿过虫洞时时间会倒流,问是否能够回到出发前的时间
Solution:
判断是否存在负环,若存在则一定能够回去。
Code:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<queue>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 3000;
int T;
int N, M, W;
struct Edge
{
int to, w, nxt;
}edge[MAXN * 2]; //双向边
int head[MAXN], t = 1;
void init()
{
memset(head, -1, sizeof(head));
t = 1;
}
void addEdge(int u, int v, int w)
{
edge[t].to = v;
edge[t].w = w;
edge[t].nxt = head[u];
head[u] = t++;
}
int vis[MAXN];
int dis[MAXN];
int cnt[MAXN]; //记录每个点经过的次数,判断是否有负环
bool spfa()
{
memset(vis, 0, sizeof(vis));
memset(dis, INF, sizeof(dis));
memset(cnt, 0, sizeof(cnt));
vis[1] = 1; dis[1] = 1; cnt[1] = 1;
queue<int> q;
q.push(1);
while(!q.empty())
{
int u = q.front(); q.pop();
vis[u] = 0; //出队,取消标记
for(int i = head[u]; i != -1; i = edge[i].nxt)
{
int to = edge[i].to;
int w = edge[i].w;
if(dis[to] > dis[u] + w)
{
dis[to] = dis[u] + w;
if(!vis[to])
{
cnt[to]++;
if(cnt[to] >= N) return true; //含有负环
vis[to] = 1;
q.push(to);
}
}
}
}
return false;
}
int main()
{
scanf("%d", &T);
while(T--)
{
init();
scanf("%d %d %d", &N, &M, &W);
int a, b, c;
for(int i = 1; i <= M; i++)
{
scanf("%d %d %d", &a, &b, &c); //双向路
addEdge(a, b, c);
addEdge(b, a, c);
}
for(int i = 1;i <= W; i++)
{
scanf("%d %d %d", &a, &b, &c);//虫洞为单向路
addEdge(a, b, -c);
}
if(spfa()) printf("YES\n");
else printf("NO\n");
}
return 0;
}