1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| #include <iostream> #include <cstdio> #include <queue> #include <climits> #define INF INT_MAX using namespace std; const int N = 110, M = 3e3 + 10; bool vis[N]; int n, m, st, d[N], cnt[N]; int idx, hd[N], nxt[M], edg[M], wt[M]; bool spfa () { for (int i = 0; i <= n + 1; i++) vis[i] = false; for (int i = 0; i <= n + 1; i++) d[i] = -INF; for (int i = 0; i <= n + 1; i++) cnt[i] = 0; queue <int> q; d[st] = 0; q.push(st); vis[st] = true; while (!q.empty()) { int t = q.front(); q.pop(); vis[t] = false; for (int i = hd[t]; ~i; i = nxt[i]) if (d[t] + wt[i] > d[edg[i]]) { d[edg[i]] = d[t] + wt[i]; cnt[edg[i]] = cnt[t] + 1; if (cnt[edg[i]] > n + 1) return false; if (!vis[edg[i]]) { q.push(edg[i]); vis[edg[i]] = true; } } } return true; } void add (int a, int b, int c) { nxt[++idx] = hd[a]; hd[a] = idx; edg[idx] = b; wt[idx] = c; } int main () { int T; cin >> T; while (T--) { cin >> n >> m; idx = -1; st = n + 1; for (int i = 0; i <= n + 1; i++) hd[i] = -1; for (int i = 0; i <= n; i++) add(st, i, 0); for (int i = 1, a, b, c; i <= m; i++) { cin >> a >> b >> c; add(a - 1, b, c); add(b, a - 1, -c); } if (spfa()) cout << "true" << endl; else cout << "false" << endl; } return 0; }
|