题意:
有向连通图(有重边)判负环。
思路:
1.bellman-ford
2.spfa
实现:
1.
1 #include <iostream> 2 #include <cstdio> 3 #include <vector> 4 using namespace std; 5 6 const int INF = 0x3f3f3f3f; 7 int d[505]; 8 struct edge 9 { 10 int s, t, w; 11 edge(int a, int b, int c) 12 { 13 s = a; t = b; w = c; 14 } 15 }; 16 vector<edge> es; 17 int t, n, m, w, a, b, l; 18 bool bellman_ford(int s) 19 { 20 for (int i = 1; i <= n; i++) 21 { 22 d[i] = INF; 23 } 24 d[s] = 0; 25 for (int i = 0; i < n - 1; i++) 26 { 27 for (int j = 0; j < es.size(); j++) 28 { 29 if (d[es[j].s] + es[j].w < d[es[j].t]) 30 { 31 d[es[j].t] = d[es[j].s] + es[j].w; 32 } 33 } 34 } 35 for (int i = 0; i < es.size(); i++) 36 { 37 if (d[es[i].s] + es[i].w < d[es[i].t]) 38 { 39 return false; 40 } 41 } 42 return true; 43 } 44 int main() 45 { 46 cin >> t; 47 while (t--) 48 { 49 es.clear(); 50 cin >> n >> m >> w; 51 for (int i = 0; i < m; i++) 52 { 53 scanf("%d %d %d", &a, &b, &l); 54 edge e(a, b, l); 55 es.push_back(e); 56 edge e1(b, a, l); 57 es.push_back(e1); 58 } 59 for (int i = 0; i < w; i++) 60 { 61 scanf("%d %d %d", &a, &b, &l); 62 edge e(a, b, -l); 63 es.push_back(e); 64 } 65 if (bellman_ford(1)) 66 { 67 cout << "NO" << endl; 68 } 69 else 70 { 71 cout << "YES" << endl; 72 } 73 } 74 return 0; 75 }
2.
1 #include <iostream> 2 #include <cstdio> 3 #include <vector> 4 #include <queue> 5 using namespace std; 6 7 const int INF = 0x3f3f3f3f; 8 int d[505], times[505]; 9 bool in[505]; 10 struct edge 11 { 12 int t, w; 13 edge(int b, int c) 14 { 15 t = b; w = c; 16 } 17 }; 18 vector<edge> G[505]; 19 int t, n, m, w, a, b, l; 20 21 bool spfa(int s) 22 { 23 for (int i = 1; i <= n; i++) 24 { 25 d[i] = INF; 26 in[i] = false; 27 times[i] = 0; 28 } 29 queue<int> q; 30 q.push(s); 31 in[s] = true; 32 d[s] = 0; 33 while (!q.empty()) 34 { 35 int tmp = q.front(); 36 q.pop(); 37 in[tmp] = false; 38 for (int i = 0; i < G[tmp].size(); i++) 39 { 40 if (d[tmp] + G[tmp][i].w < d[G[tmp][i].t]) 41 { 42 d[G[tmp][i].t] = d[tmp] + G[tmp][i].w; 43 times[G[tmp][i].t]++; 44 if (times[G[tmp][i].t] == n) 45 { 46 return false; 47 } 48 if (!in[G[tmp][i].t]) 49 { 50 in[G[tmp][i].t] = true; 51 q.push(G[tmp][i].t); 52 } 53 } 54 } 55 } 56 return true; 57 } 58 59 int main() 60 { 61 cin >> t; 62 while (t--) 63 { 64 for (int i = 1; i <= n; i++) 65 { 66 G[i].clear(); 67 } 68 cin >> n >> m >> w; 69 for (int i = 0; i < m; i++) 70 { 71 scanf("%d %d %d", &a, &b, &l); 72 edge e(b, l); 73 G[a].push_back(e); 74 edge e1(a, l); 75 G[b].push_back(e1); 76 } 77 for (int i = 0; i < w; i++) 78 { 79 scanf("%d %d %d", &a, &b, &l); 80 edge e(b, -l); 81 G[a].push_back(e); 82 } 83 if (spfa(1)) 84 { 85 cout << "NO" << endl; 86 } 87 else 88 { 89 cout << "YES" << endl; 90 } 91 } 92 return 0; 93 }