AtCoder Beginner Contest 061 D Score Attack(Bellman-ford)

点击打开题目链接

D – Score Attack

Time limit : 2sec / Memory limit : 256MB

Score : 400 points

Problem Statement

There is a directed graph with N vertices and M edges. The i-th edge (1iM) points from vertex ai to vertex bi, and has a weight ci. We will play the following single-player game using this graph and a piece.

Initially, the piece is placed at vertex 1, and the score of the player is set to 0. The player can move the piece as follows:

  • When the piece is placed at vertex ai, move the piece along the i-th edge to vertex bi. After this move, the score of the player is increased by ci.

The player can end the game only when the piece is placed at vertex N. The given graph guarantees that it is possible to traverse from vertex 1 to vertex N.

When the player acts optimally to maximize the score at the end of the game, what will the score be? If it is possible to increase the score indefinitely, print inf.

Constraints

  • 2N1000
  • 1Mmin(N(N1),2000)
  • 1ai,biN(1iM)
  • aibi(1iM)
  • aiaj or bibj(1i<jM)
  • −109ci109(1iM)
  • ci is an integer.
  • In the given graph, there exists a path from vertex 1 to vertex N.

Input

Input is given from Standard Input in the following format:

N M  
a1 b1 c1  
a2 b2 c2
:  
aM bM cM  

Output

Print the maximum possible score at the end of the game, if it is finite. If it is possible to increase the score indefinitely, print inf.

Sample Input 1

Copy

3 3
1 2 4
2 3 3
1 3 5

Sample Output 1

Copy

7

There are two ways to move the piece to vertex N=3:

  • vertex 1 → vertex 2 → vertex 3 : score 4+3=7
  • vertex 1 → vertex 3 : score 5

Thus, the maximum possible score at the end of the game is 7.

Sample Input 2

Copy

2 2
1 2 1
2 1 1

Sample Output 2

Copy

inf

It is possible to increase the score indefinitely by alternating between vertex 1 and 2.

Sample Input 3

Copy

6 5
1 2 -1000000000
2 3 -1000000000
3 4 -1000000000
4 5 -1000000000
5 6 -1000000000

Sample Output 3

Copy

-5000000000

Submit

题目大意:找从起点到终点的最长路径。

Bellman-ford算法。想起刚过去的省赛热身赛的A题,同样的方法用了第二次。如果N-1次更新与2*N-1次更新结果相同,即不存在环无限循环的情况。

附上AC代码:

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;
typedef long long ll;
const int maxn = 2000 + 5;
const ll oo = 0x3f3f3f3f3f3f3f3f;
int N, M;
ll d1, d2;

int main()
{
	while (cin >> N >> M)
	{
		vector<int>a(M);
		vector<int>b(M);
		vector<ll>c(M);
		for (int i = 0; i < M; i++)
		{
			cin >> a[i] >> b[i] >> c[i];
			a[i]--,	b[i]--;
		}
		vector<ll>d(N, -oo);
		d[0] = 0LL;
		for (int i = 0; i < 2 * N; i++)
		{
			for (int j = 0; j < M; j++)
			{
				d[b[j]] = max(d[b[j]], d[a[j]] + c[j]);
			}
			if (i == N - 1)
				d1 = d[N - 1];
			if (i == 2 * N - 1)
				d2 = d[N - 1];
		}
		if (d1 == d2)
			cout << d1 << endl;
		else
			cout << "inf" << endl;
	}
	return 0;
}

    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/l1832876815/article/details/71911200
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞