import java.util.*;
public class BellmanFord {
static boolean debug = false;
static class Edge {
int from, to, cost;
public Edge(int from,int to,int cost) {
this.from = from; this.to = to; this.cost = cost;
}
public String toString() { return "edge["+from+", "+to+", "+cost+"]"; }
}
int MAX_V;
ArrayList<Edge> edges;
int[] distance;
public BellmanFord(int n,int m) {
MAX_V = n;
edges = new ArrayList<Edge>();
distance = new int[n];
}
public void addEdge(int from, int to, int cost) {
edges.add(new Edge(from,to,cost));
}
public void shortestPath(int src, int dst) {
for (int i=0; i<distance.length; i++) distance[i] = Integer.MAX_VALUE;
distance[src] = 0;
int count = 0;
boolean updated = true;
while (updated) {
updated = false;
for (Edge e: edges) {
if (distance[e.from] != Integer.MAX_VALUE
&& distance[e.to] > distance[e.from] + e.cost) {
distance[e.to] = distance[e.from] + e.cost;
updated = true;
if (count == MAX_V-1) throw new RuntimeException("negative loop");
}
}
count ++;
}
}
public static void main(String[] args) {
for (int i=0; i<args.length; i++) {
if (args[i].equals("-d")) debug = !debug;
}
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt();
BellmanFord bf = new BellmanFord(n, m);
for (int i=0; i<m; i++) {
int from = sc.nextInt(), to = sc.nextInt(), cost = sc.nextInt();
bf.addEdge(from,to,cost);
}
int src = sc.nextInt(), dst = sc.nextInt();
try {
bf.shortestPath(src,dst);
System.out.println(bf.distance[dst]);
} catch (Exception e) {
System.out.println("negative loop");
}
if (debug) {
for (int i=0; i<bf.MAX_V; i++) System.out.print(bf.distance[i]+" ");
System.out.println();
}
}
}
|