-
Notifications
You must be signed in to change notification settings - Fork 69
/
HighScore.java
75 lines (65 loc) Β· 1.89 KB
/
HighScore.java
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
66
67
68
69
70
71
72
73
74
75
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
class Custom {
int from;
int to;
int weight;
public Custom(int from, int to, int weight) {
this.from = from;
this.to = to;
this.weight = weight;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int max = (int) 1e17;
int min = (int) -1e17;
int n = scanner.nextInt();
int m = scanner.nextInt();
ArrayList<Custom> edges = new ArrayList<>();
for (int i = 0; i < m; i++) {
int from = scanner.nextInt();
int to = scanner.nextInt();
int weight = scanner.nextInt();
weight *= -1;
edges.add(new Custom(from, to, weight));
}
int[] dist = new int[n + 1];
Arrays.fill(dist, max);
dist[1] = 0;
// Bellman-Ford Algorithm
for (int i = 0; i < n; i++) {
for (Custom e : edges) {
int u = e.from;
int v = e.to;
int w = e.weight;
if (dist[u] == max) {
continue;
}
dist[v] = Math.min(dist[v], dist[u] + w);
dist[v] = Math.max(dist[v], min);
}
}
for (int i = 0; i < n; i++) {
for (Custom e : edges) {
int u = e.from;
int v = e.to;
int w = e.weight;
if (dist[u] == max) {
continue;
}
dist[v] = Math.max(dist[v],min);
if (dist[v] > dist[u] + w) {
dist[v] = min;
}
}
}
if (dist[n] == min || dist[n] == max) {
System.out.println(-1);
} else {
System.out.println(-1 * dist[n]);
}
}
}