存在正环或负环的最短路问题
Bellman-ford不存在环时第n次更新与第n*2次更新结果一样;如果第n次更新和第n*2次更新结果不同,说明存在环。
Sample Input 1
3 3
1 2 4
2 3 3
1 3 5
Sample Output 1
7
Sample Input 2
2 2
1 2 1
2 1 1
Sample Output 2
inf
Sample Input 3
6 5
1 2 -1000000000
2 3 -1000000000
3 4 -1000000000
4 5 -1000000000
5 6 -1000000000
Sample Output 3
-5000000000
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct edge {
int x, y, z;
} a[2001];
int n, m;
ll dis[1001], d1, d2;
inline void init() {
for (int i = 1; i <= n; i++)
dis[i] = -1LL << 60;
dis[1] = 0;
}
int main() {
while (cin >> n >> m) {
for (int i = 1; i <= m; i++)
scanf("%d%d%d", &a[i].x, &a[i].y, &a[i].z);
init();
for (int i = 1; i <= n * 2; i++)
for (int j = 1; j <= m; j++) {
int x = a[j].x, y = a[j].y, z = a[j].z;
dis[y] = max(dis[y], dis[x] + z);
if (i == n)
d1 = dis[n];
if (i == n * 2)
d2 = dis[n];
}
if (d1 == d2)
printf("%lld\n", dis[n]);
else
printf("inf\n");
}
return 0;
}