题意:给你一个有向带负权图, 问其中存不存在负环。
思路:用bellman-ford算法松弛n-1次,然后在第n次时判断是不是还有点能松弛,若还能松弛则说明存在负环。
代码如下:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <cmath> 6 #include <algorithm> 7 #include <vector> 8 #include <queue> 9 #include <stack> 10 #define INF 0x7fffffff 11 #define LEN 5101 12 #define ll long long 13 using namespace std; 14 15 ll n, m, u[LEN], v[LEN], w[LEN], dis[LEN]; 16 17 int main() 18 { 19 // freopen("in.txt", "r", stdin); 20 int T; 21 scanf("%d", &T); 22 while(T--){ 23 scanf("%lld%lld", &n, &m); 24 for(int i=0; i<LEN; i++)dis[i] = INF; 25 dis[0] = 0; 26 for(int i=0; i<m; i++){ 27 scanf("%lld%lld%lld", &u[i], &v[i], &w[i]); 28 } 29 for(int i=0; i<n-1; i++){ 30 for(int j=0; j<m; j++){ 31 int x = u[j], y = v[j]; 32 if(dis[y]>dis[x]+w[j])dis[y] = dis[x]+w[j]; 33 } 34 } 35 int ans = 0; 36 for(int i=0; i<m; i++){ 37 int x = u[i], y = v[i]; 38 if(dis[y]>dis[x]+w[i]){ans = 1;break;} 39 } 40 if(ans)printf("possible "); 41 else printf("not possible "); 42 } 43 return 0; 44 }