I was trying to implement MST with Priorityqueue with custom comparator, but I am facing problem in building min-heap with it in O(n) time. The problem is only one constructor of Priorityqueue allows to create PriorityQueue in O(n), but it does not take any comparator as argument. I want it to use my custom comparator. Is there workaround for this problem ? PriorityQueue.addAll() will lose the purpose of using Min-heap for MST as it is O(nlogn) method. Here is my code.
ArrayList <edge>ar=new ArrayList<>();
for(int i=0;i<e;i++)
{
int u=ss.nextInt();
int v=ss.nextInt();
int w=ss.nextInt();
ar.add(new edge(u,v,w));
}
PriorityQueue <edge>pr=new PriorityQueue<edge>(ar);
And the comparator that I want to use:-
PriorityQueue <edge>ar=new PriorityQueue(11,new Comparator() {
@Override
public int compare(Object o1, Object o2) {
edge n1=(edge) o1;
edge n2=(edge) o2;
if(n1.w<n2.w)
{
return -1;
}
else if(n1.w==n2.w)
{
if((n1.u+n1.v+n1.w)<=(n2.u+n2.v+n2.w))
{
return -1;
}
else
{
return 1;
}
}
else
{
return 1;
}
}
});
O(n)
time from scratch... been a while since I was in Data Structures!! :) – ExsanguinePriorityQueue
inheritsaddAll
fromAbstractQueue
. It does not override the implementation. Documentation forAbstractQueue.addAll
says, This implementation iterates over the specified collection, and adds each element returned by the iterator to this queue, in turn. That'll be O(n log n). – VariegationaddAll
usesfor(E e : c) add(e)
- noheapify
involved - there's nothing to stop it from appending to the array and calling a single heapify though, which in all honesty I'm surprised it doesn't do, even if truth be told the difference betweenn
andn lg n
is pretty darned small. – Exsanguine