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
Line 1 of each farm: Three space-separated integers respectively: N, M, and W
Lines 2.. M+1 of each farm: Three space-separated numbers ( S, E, T) that describe, respectively: a bidirectional path between S and E that requires T seconds to traverse. Two fields might be connected by more than one path.
Lines M+2.. M+ W+1 of each farm: Three space-separated numbers ( S, E, T) that describe, respectively: A one way path from S to E that also moves the traveler back T seconds.
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
题解:构图,判断图中有没有负环即可,bellman-ford和spfa都可以。坑的是路径是双向的,虫洞是单向的。。。
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <list>
#include <set>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <functional>
#include <iomanip>
#include <limits>
#include <new>
#include <utility>
#include <iterator>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <ctime>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 510;
struct edge
{
int v, d;
};
vector<edge> G[maxn];
int vis[maxn], cnt[maxn], d[maxn];
int n, m, w;
bool spfa(int s)
{
queue<int> q;
memset(vis, 0, sizeof(vis));
memset(cnt, 0, sizeof(cnt));
fill(d, d+n, INF);
d[s] = 0;
q.push(s);
while (!q.empty())
{
int u = q.front();
q.pop();
vis[u] = 0;
for (int i = 0; i < G[u].size(); ++i)
{
int v = G[u][i].v, dis = G[u][i].d;
if (d[v] > d[u] + dis)
{
d[v] = d[u] + dis;
if (!vis[v])
{
q.push(v);
vis[v] = 1;
if (++cnt[v] > n)
return false;
}
}
}
}
return true;
}
int main()
{
int T;
cin >> T;
while (T--)
{
cin >> n >> m >> w;
for (int i = 0; i < n; ++i)
G[i].clear();
while (m--)
{
int u, v, d;
scanf("%d%d%d", &u, &v, &d);
G[u-1].push_back({v-1, d});
G[v-1].push_back({u-1, d});
}
while (w--)
{
int u, v, d;
scanf("%d%d%d", &u, &v, &d);
G[u-1].push_back({v-1, -d});
}
if (spfa(0))
printf("NO
");
else
printf("YES
");
}
return 0;
}