forked from Jonathan-Uy/CSES-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHigh Score.cpp
65 lines (55 loc) · 1.29 KB
/
High Score.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxN = 2501;
const int maxM = 5001;
const ll INF = 0x3f3f3f3f3f3f3f3f;
struct Edge {
int a, b; ll c;
} edges[maxM];
int N, M;
ll dp[maxN];
bool vis[maxN], visR[maxN];
vector<int> G[maxN], GR[maxN];
void dfs(int u){
vis[u] = true;
for(int v : G[u])
if(!vis[v])
dfs(v);
}
void dfsR(int u){
visR[u] = true;
for(int v : GR[u])
if(!visR[v])
dfsR(v);
}
int main(){
scanf("%d %d", &N, &M);
for(int i = 0, a, b; i < M; i++){
ll c;
scanf("%d %d %lld", &a, &b, &c);
edges[i] = {a, b, -c};
G[a].push_back(b);
GR[b].push_back(a);
}
dfs(1); dfsR(N);
fill(dp+2, dp+N+1, INF);
bool improvement = true;
for(int iter = 0; iter < N && improvement; iter++){
improvement = false;
for(int i = 0; i < M; i++){
int u = edges[i].a;
int v = edges[i].b;
ll w = edges[i].c;
if(dp[v] > dp[u]+w){
dp[v] = dp[u]+w;
improvement = true;
if(iter == N-1 && vis[v] && visR[v]){
printf("-1\n");
return 0;
}
}
}
}
printf("%lld\n", -dp[N]);
}