package algs43;
import stdlib.*;
import algs13.Queue;
import algs15.WeightedUF;
import algs24.MinPQ;
/* ***********************************************************************
 *  Compilation:  javac LazyPrimMST.java
 *  Execution:    java LazyPrimMST filename.txt
 *  Dependencies: EdgeWeightedGraph.java Edge.java Queue.java
 *                MinPQ.java UF.java In.java StdOut.java
 *  Data files:   http://algs4.cs.princeton.edu/43mst/tinyEWG.txt
 *                http://algs4.cs.princeton.edu/43mst/mediumEWG.txt
 *                http://algs4.cs.princeton.edu/43mst/largeEWG.txt
 *
 *  Compute a minimum spanning forest using a lazy version of Prim's
 *  algorithm.
 *
 *  %  java LazyPrimMST tinyEWG.txt
 *  0-7 0.16000
 *  1-7 0.19000
 *  0-2 0.26000
 *  2-3 0.17000
 *  5-7 0.28000
 *  4-5 0.35000
 *  6-2 0.40000
 *  1.81000
 *
 *  % java LazyPrimMST mediumEWG.txt
 *  0-225   0.02383
 *  49-225  0.03314
 *  44-49   0.02107
 *  44-204  0.01774
 *  49-97   0.03121
 *  202-204 0.04207
 *  176-202 0.04299
 *  176-191 0.02089
 *  68-176  0.04396
 *  58-68   0.04795
 *  10.46351
 *
 *  % java LazyPrimMST largeEWG.txt
 *  ...
 *  647.66307
 *
 *************************************************************************/

public class LazyPrimMST {
	private double weight;       // total weight of MST
	private final Queue<Edge> mst;     // edges in the MST
	private final boolean[] marked;    // marked[v] = true if v on tree
	private final MinPQ<Edge> pq;      // edges with one endpoint in tree

	// compute minimum spanning forest of G
	public LazyPrimMST(EdgeWeightedGraph G) {
		mst = new Queue<>();
		pq = new MinPQ<>();
		marked = new boolean[G.V()];
		for (int v = 0; v < G.V(); v++)     // run Prim from all vertices to
			if (!marked[v]) prim(G, v);     // get a minimum spanning forest

		// check optimality conditions
		assert check(G);
	}

	// run Prim's algorithm
	private void prim(EdgeWeightedGraph G, int s) {
		scan(G, s);
		while (!pq.isEmpty()) {                        // better to stop when mst has V-1 edges
			Edge e = pq.delMin();                      // smallest edge on pq
			int v = e.either(), w = e.other(v);        // two endpoints
			assert marked[v] || marked[w];
			if (marked[v] && marked[w]) continue;      // lazy, both v and w already scanned
			mst.enqueue(e);                            // add e to MST
			weight += e.weight();
			if (!marked[v]) scan(G, v);               // v becomes part of tree
			if (!marked[w]) scan(G, w);               // w becomes part of tree
		}
	}

	// add all edges e incident to v onto pq if the other endpoint has not yet been scanned
	private void scan(EdgeWeightedGraph G, int v) {
		assert !marked[v];
		marked[v] = true;
		for (Edge e : G.adj(v))
			if (!marked[e.other(v)]) pq.insert(e);
	}

	// return edges in MST as an Iterable
	public Iterable<Edge> edges() {
		return mst;
	}

	// return weight of MST
	public double weight() {
		return weight;
	}

	// check optimality conditions (takes time proportional to E V lg* V)
	private boolean check(EdgeWeightedGraph G) {

		// check weight
		double totalWeight = 0.0;
		for (Edge e : edges()) {
			totalWeight += e.weight();
		}
		double EPSILON = 1E-12;
		if (Math.abs(totalWeight - weight()) > EPSILON) {
			System.err.format("Weight of edges does not equal weight(): %f vs. %f\n", totalWeight, weight());
			return false;
		}

		// check that it is acyclic
		WeightedUF uf = new WeightedUF(G.V());
		for (Edge e : edges()) {
			int v = e.either(), w = e.other(v);
			if (uf.connected(v, w)) {
				System.err.println("Not a forest");
				return false;
			}
			uf.union(v, w);
		}

		// check that it is a spanning forest
		for (Edge e : edges()) {
			int v = e.either(), w = e.other(v);
			if (!uf.connected(v, w)) {
				System.err.println("Not a spanning forest");
				return false;
			}
		}

		// check that it is a minimal spanning forest (cut optimality conditions)
		for (Edge e : edges()) {
			int v = e.either(), w = e.other(v);

			// all edges in MST except e
			uf = new WeightedUF(G.V());
			for (Edge f : mst) {
				int x = f.either(), y = f.other(x);
				if (f != e) uf.union(x, y);
			}

			// check that e is min weight edge in crossing cut
			for (Edge f : G.edges()) {
				int x = f.either(), y = f.other(x);
				if (!uf.connected(x, y)) {
					if (f.weight() < e.weight()) {
						System.err.println("Edge " + f + " violates cut optimality conditions");
						return false;
					}
				}
			}

		}

		return true;
	}


	public static void main(String[] args) {
		In in = new In(args[0]);
		EdgeWeightedGraph G = new EdgeWeightedGraph(in);
		LazyPrimMST mst = new LazyPrimMST(G);
		for (Edge e : mst.edges()) {
			StdOut.println(e);
		}
		StdOut.format("%.5f\n", mst.weight());
	}

}
