D - Score Attack

D - Score Attack (atcoder.jp)

存在正环或负环的最短路问题

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;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值