Skip to content

Commit

Permalink
Merge pull request #203 from sejalphatangare/sejalphatangare-patch-2
Browse files Browse the repository at this point in the history
#154 High Score
  • Loading branch information
Gdsc-Cummins authored Oct 21, 2023
2 parents b44f580 + 2ac0bd5 commit 0f551cb
Showing 1 changed file with 75 additions and 0 deletions.
75 changes: 75 additions & 0 deletions HighScore.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,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]);
}
}
}

0 comments on commit 0f551cb

Please sign in to comment.