星球間有雙向道路(正權)與單向蟲洞(負權)。判斷是否存在負權環(即可時間旅行)。多測資,輸出 YES/NO。
#include
#include
#include
#include
#include
#include
using namespace std;
const int SIZE = 11111;
const int MAXLEN = 1<<30;
struct Edge { int s, e, v; } ed[SIZE];
int N, M, WH, dis[SIZE], ednum;
bool Bellman() {
for (int i = 0; i < N-1; i++) {
bool flag = false;
for (int j = 0; j < ednum; j++) {
if (dis[ed[j].e] > dis[ed[j].s] + ed[j].v) {
flag = true;
dis[ed[j].e] = dis[ed[j].s] + ed[j].v;
}
}
if (!flag) break;
}
for (int j = 0; j < ednum; j++)
if (dis[ed[j].e] > dis[ed[j].s] + ed[j].v)
return true;
return false;
}
int main() {
int f, u, v, w;
cin >> f;
while (f--) {
ednum = 0;
cin >> N >> M >> WH;
for (int i = 0; i < M; i++) {
cin >> u >> v >> w;
ed[ednum++] = {u, v, w};
ed[ednum++] = {v, u, w};
}
for (int i = 0; i < WH; i++) {
cin >> u >> v >> w;
ed[ednum++] = {u, v, -w};
}
if (Bellman()) printf("YES\n"); else printf("NO\n");
}
return 0;
}
O(V·E),V≤500,E≤2500,極快。