First, we implement the usual Prim-algorithm with a priority queue, which runs in O (| E | log (| V |)). And do it yourself, instead of copying the book code. If you cannot implement Prim Algorithm yourself, you will not understand how to extend the algorithm.
Then, as the DW suggested at https://cs.stackexchange.com/questions/66498/prims-algorithm-on-graph-with-weights-of-only-1-and-2-on-each-edge , you can change its ExtractMin, Remove, and Insert functions to O (1).
The idea is that you can save the list of edges with weights 1 and 2. If the list for the weight of edge 1 is not empty, you can get the next best edge to use by selecting the list in O (1) time. If the list for the weight of the edge 1 is empty, then the next best edges can be obtained by setting the list of weights 2 O (1) times.
The only change from the usual Prim algorithm is that you need a data structure like this:
private class SpecialPQ { ArrayList<NodeWeightPair> _queueWeight1 = new ArrayList<NodeWeightPair>(); ArrayList<NodeWeightPair> _queueWeight2 = new ArrayList<NodeWeightPair>(); public void insert(NodeWeightPair e) { if (e._weight == 1) { _queueWeight1.add(e); } else { _queueWeight2.add(e); } } public void remove() { if (_queueWeight1.size() == 0) { _queueWeight2.remove(_queueWeight2.size()-1); } else { _queueWeight1.remove(_queueWeight1.size()-1); } } public NodeWeightPair extractMin() { if (_queueWeight1.size() > 0) { return _queueWeight1.get(_queueWeight1.size()-1); } else { return _queueWeight2.get(_queueWeight2.size()-1); } } public boolean empty() { return _queueWeight1.size() == 0 && _queueWeight2.size() == 0; } };
The Normal Prim Algorithm uses the binary heap priority queue to get O (| E | log (| V |)). You just need to replace the binary heap priority queue with the faster SpecialPQ .
Thus, the book code has the following line:
private IndexMinPQ<Double> pq;
You just need to change this to
private SpecialPQ pq;
and get the rest of the code to compile. Do not arbitrarily copy and paste my code for SpecialPQ . You will need a lot of time to be compatible with the book code. Instead, I think you should write your own SpecialPQ that will work with your own implementation of Prim Algorithm.
I have a working example locally - my own implementation, so it is not compatible with the book code. I will share with you if you publish your attempt to implement this.
Changes:
NodeWeightPair
private class NodeWeightPair { private int _parent; private int _node; private int _weight; public NodeWeightPair(int parent, int node, int weight) { _node = node; _weight = weight; _parent = parent; } }