// check that algorithm computes either the topological order or finds a directed cycle private void dfs(EdgeWeightedDigraph G, int v) { onStack[v] = true; marked[v] = true; for (DirectedEdge e : G.adj(v)) { int w = e.to(); // short circuit if directed cycle found if (cycle != null) return; // found new vertex, so recur else if (!marked[w]) { edgeTo[w] = e; dfs(G, w); } // trace back directed cycle else if (onStack[w]) { cycle = new Stack<DirectedEdge>(); DirectedEdge f = e; while (f.from() != w) { cycle.push(f); f = edgeTo[f.from()]; } cycle.push(f); return; } } onStack[v] = false; }
// relax edge e, but update if you find a *longer* path private void relax(DirectedEdge e) { int v = e.from(), w = e.to(); if (distTo[w] < distTo[v] + e.weight()) { distTo[w] = distTo[v] + e.weight(); edgeTo[w] = e; } }
/** * Reads the currency exchange table from standard input and * prints an arbitrage opportunity to standard output (if one exists). * * @param args the command-line arguments */ public static void main(String[] args) { // V currencies int V = StdIn.readInt(); String[] name = new String[V]; // create complete network EdgeWeightedDigraph G = new EdgeWeightedDigraph(V); for (int v = 0; v < V; v++) { name[v] = StdIn.readString(); for (int w = 0; w < V; w++) { double rate = StdIn.readDouble(); DirectedEdge e = new DirectedEdge(v, w, -Math.log(rate)); G.addEdge(e); } } // find negative cycle BellmanFordSP spt = new BellmanFordSP(G, 0); if (spt.hasNegativeCycle()) { double stake = 1000.0; for (DirectedEdge e : spt.negativeCycle()) { StdOut.printf("%10.5f %s ", stake, name[e.from()]); stake *= Math.exp(-e.weight()); StdOut.printf("= %10.5f %s\n", stake, name[e.to()]); } } else { StdOut.println("No arbitrage opportunity"); } }
// certify that digraph is either acyclic or has a directed cycle private boolean check() { // edge-weighted digraph is cyclic if (hasCycle()) { // verify cycle DirectedEdge first = null, last = null; for (DirectedEdge e : cycle()) { if (first == null) first = e; if (last != null) { if (last.to() != e.from()) { System.err.printf("cycle edges %s and %s not incident\n", last, e); return false; } } last = e; } if (last.to() != first.from()) { System.err.printf("cycle edges %s and %s not incident\n", last, first); return false; } } return true; }
// check optimality conditions: either // (i) there exists a negative cycle reacheable from s // or // (ii) for all edges e = v->w: distTo[w] <= distTo[v] + e.weight() // (ii') for all edges e = v->w on the SPT: distTo[w] == distTo[v] + e.weight() private boolean check(EdgeWeightedDigraph G, int s) { // has a negative cycle if (hasNegativeCycle()) { double weight = 0.0; for (DirectedEdge e : negativeCycle()) { weight += e.weight(); } if (weight >= 0.0) { System.err.println("error: weight of negative cycle = " + weight); return false; } } // no negative cycle reachable from source else { // check that distTo[v] and edgeTo[v] are consistent if (distTo[s] != 0.0 || edgeTo[s] != null) { System.err.println("distanceTo[s] and edgeTo[s] inconsistent"); return false; } for (int v = 0; v < G.V(); v++) { if (v == s) continue; if (edgeTo[v] == null && distTo[v] != Double.POSITIVE_INFINITY) { System.err.println("distTo[] and edgeTo[] inconsistent"); return false; } } // check that all edges e = v->w satisfy distTo[w] <= distTo[v] + e.weight() for (int v = 0; v < G.V(); v++) { for (DirectedEdge e : G.adj(v)) { int w = e.to(); if (distTo[v] + e.weight() < distTo[w]) { System.err.println("edge " + e + " not relaxed"); return false; } } } // check that all edges e = v->w on SPT satisfy distTo[w] == distTo[v] + e.weight() for (int w = 0; w < G.V(); w++) { if (edgeTo[w] == null) continue; DirectedEdge e = edgeTo[w]; int v = e.from(); if (w != e.to()) return false; if (distTo[v] + e.weight() != distTo[w]) { System.err.println("edge " + e + " on shortest path not tight"); return false; } } } StdOut.println("Satisfies optimality conditions"); StdOut.println(); return true; }
/** * Adds the directed edge {@code e} to this edge-weighted digraph. * * @param e the edge * @throws IllegalArgumentException unless endpoints of edge are between {@code 0} * and {@code V-1} */ public void addEdge(DirectedEdge e) { int v = e.from(); int w = e.to(); validateVertex(v); validateVertex(w); adj[v].add(e); indegree[w]++; E++; }
/** * Returns a shortest path from the source vertex {@code s} to vertex {@code v}. * @param v the destination vertex * @return a shortest path from the source vertex {@code s} to vertex {@code v} * as an iterable of edges, and {@code null} if no such path * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public Iterable<DirectedEdge> pathTo(int v) { validateVertex(v); if (!hasPathTo(v)) return null; Stack<DirectedEdge> path = new Stack<DirectedEdge>(); for (DirectedEdge e = edgeTo[v]; e != null; e = edgeTo[e.from()]) { path.push(e); } return path; }
// relax edge e and update pq if changed private void relax(DirectedEdge e) { int v = e.from(), w = e.to(); if (distTo[w] > distTo[v] + e.weight()) { distTo[w] = distTo[v] + e.weight(); edgeTo[w] = e; if (pq.contains(w)) pq.decreaseKey(w, distTo[w]); else pq.insert(w, distTo[w]); } }
/** * Adds the directed edge {@code e} to the edge-weighted digraph (if there * is not already an edge with the same endpoints). * @param e the edge */ public void addEdge(DirectedEdge e) { int v = e.from(); int w = e.to(); validateVertex(v); validateVertex(w); if (adj[v][w] == null) { E++; adj[v][w] = e; } }
/** * Returns a shortest path from the source {@code s} to vertex {@code v}. * @param v the destination vertex * @return a shortest path from the source {@code s} to vertex {@code v} * as an iterable of edges, and {@code null} if no such path * @throws UnsupportedOperationException if there is a negative cost cycle reachable * from the source vertex {@code s} * @throws IllegalArgumentException unless {@code 0 <= v < V} */ public Iterable<DirectedEdge> pathTo(int v) { validateVertex(v); if (hasNegativeCycle()) throw new UnsupportedOperationException("Negative cost cycle exists"); if (!hasPathTo(v)) return null; Stack<DirectedEdge> path = new Stack<DirectedEdge>(); for (DirectedEdge e = edgeTo[v]; e != null; e = edgeTo[e.from()]) { path.push(e); } return path; }
// check optimality conditions: // (i) for all edges e: distTo[e.to()] <= distTo[e.from()] + e.weight() // (ii) for all edge e on the SPT: distTo[e.to()] == distTo[e.from()] + e.weight() private boolean check(EdgeWeightedDigraph G, int s) { // check that edge weights are nonnegative for (DirectedEdge e : G.edges()) { if (e.weight() < 0) { System.err.println("negative edge weight detected"); return false; } } // check that distTo[v] and edgeTo[v] are consistent if (distTo[s] != 0.0 || edgeTo[s] != null) { System.err.println("distTo[s] and edgeTo[s] inconsistent"); return false; } for (int v = 0; v < G.V(); v++) { if (v == s) continue; if (edgeTo[v] == null && distTo[v] != Double.POSITIVE_INFINITY) { System.err.println("distTo[] and edgeTo[] inconsistent"); return false; } } // check that all edges e = v->w satisfy distTo[w] <= distTo[v] + e.weight() for (int v = 0; v < G.V(); v++) { for (DirectedEdge e : G.adj(v)) { int w = e.to(); if (distTo[v] + e.weight() < distTo[w]) { System.err.println("edge " + e + " not relaxed"); return false; } } } // check that all edges e = v->w on SPT satisfy distTo[w] == distTo[v] + e.weight() for (int w = 0; w < G.V(); w++) { if (edgeTo[w] == null) continue; DirectedEdge e = edgeTo[w]; int v = e.from(); if (w != e.to()) return false; if (distTo[v] + e.weight() != distTo[w]) { System.err.println("edge " + e + " on shortest path not tight"); return false; } } return true; }