题意:利用虫洞进行时间旅行,问是否可以碰到以前的自己。
输入为M条双向边和W条单向边。双向边表示农夫从一个虫洞走到另一个虫洞需要的时间,单向边表示可以从虫洞穿越到另一个虫洞,并回到T秒前。
思路:BellmanFord求负环。难在理解输入。
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <queue>
#include <set>
#include <map>
using namespace std;
int N,M,W;
int D[6000][2];
int C[6000];
int tol;
const int inf = 0x3f3f3f3f;
bool Bellman()
{
int dis[6000];
int book[6000];
for (int i = 1; i <= N; i++)
dis[i] = 0;
//dis[1] = inf;
memset(book,0,sizeof(book));
bool flag = true;
int cnt = 0;
while (flag)
{
if (cnt++>=N)
return true;
flag = false;
for (int j = 0; j < tol; j++)
{
int u = D[j][0];
int v = D[j][1];
if (dis[v] > dis[u]+C[j])
{
dis[v] = dis[u]+C[j];
flag = true;
}
}
}
}
int main(void)
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int T;
scanf("%d", &T);
while (T--)
{
memset(D,inf,sizeof(D));
memset(C,inf,sizeof(C));
tol = 0;
scanf("%d %d %d", &N, &M, &W);
while (M--)
{
int x, y, s;
scanf("%d %d %d", &x, &y, &s);
D[tol][0] = x;
D[tol][1] = y;
C[tol] = s;
tol++;
D[tol][0] = y;
D[tol][1] = x;
C[tol] = s;
tol++;
}
while (W--)
{
int x, y, s;
scanf("%d %d %d", &x, &y, &s);
D[tol][0] = x;
D[tol][1] = y;
C[tol] = -s;
tol++;
}
if (Bellman())
printf("YES\n");
else
printf("NO\n");
}
return 0;
}