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 77 78 79 80 81 82 83 84 85 86
| #include <iostream> #include <queue> #include <iostream> #include <cstring>
using namespace std;
const int N = 1e5 + 10;
int n, m; int h[N], e[N], ne[N], w[N], idx; int dist[N]; int cnt[N]; bool st[N];
void add(int a, int b, int c) { e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ; }
bool spfa() { memset(dist, 0x3f, sizeof(dist)); memset(cnt, 0, sizeof(cnt)); queue <int> q; dist[1] = 0; for(int i = 1; i <= n; i ++ ) { q.push(i); st[i] = true; } while(q.size()) { int t = q.front(); q.pop(); st[t] = false; for(int i = h[t]; i != -1; i = ne[i]) { int j = e[i]; if(dist[j] > dist[t] + w[i]) { dist[j] = dist[t] + w[i]; cnt[j] = cnt[t] + 1; if(cnt[j] >= n) return true; if(!st[j]) { q.push(j); st[j] = true; } } } } return false; }
int main() { int t; cin >> t; while(t -- ) { memset(h, -1, sizeof(h)); memset(e, 0, sizeof(e)); memset(ne, 0, sizeof(ne)); memset(w, 0, sizeof(w)); memset(st, 0, sizeof(st)); idx = 0; cin >> n >> m; while(m -- ) { int a, b, w; cin >> a >> b >> w; if(w >= 0) { add(a, b, w); add(b, a, w); } else add(a, b, w); } if(spfa()) printf("YES\n"); else printf("NO\n"); } return 0; }
|