Create PriorityQueue in O (n) using custom comparator

I tried to implement MST with Priorityqueue using a custom comparator, but I have to deal with the problem of creating a min-heap with it in O (n) time. The problem is only one Priorityqueue constructor, which allows you to create a PriorityQueue in O (n), but it does not accept any comparator as an argument. I want him to use my own comparator. Is there a workaround for this problem? PriorityQueue.addAll () will lose the purpose of using the Min-heap for MST, since it is an 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 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;
            }
        }
    });
+4
source share
2 answers

- , new PriorityQueue(...) - - . O(n) , , .

PriorityQueue<edge> pr = new PriorityQueue<edge>(ar, comp) {
    PriorityQueue(List<edge> ar, Comparator<edge> c) {
        this(c);
        for(int i = 0; i < queue.length; i++) {
            queue[i] = ar.get(i);
        }
        this.size = queue.length;
        heapify(); // O(n), except that heapify is private and thus you can't call it!!!
    }
}

, PriorityQueue, .

- -, , . O(n), - heapify.

edge Comparable<edge>. PriorityQueue<edge> pr = new PriorityQueue(ar);

edge implements Comparable<edge>, :

class EdgeContainer implements Comparable<EdgeContainer> {

    private static final Comparator<edge> comp = ; // that comparator above
    private final edge edge;
    EdgeContainer(Edge edge) { this.edge = edge; }
    public int compareTo(EdgeContainer e) { return comp.compare(edge, e.edge); }
    public edge getEdge() { return edge; }
}

List <EdgeContainer>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 EdgeContainer(new edge(u,v,w)));
}

PriorityQueue<EdgeContainer> qr = new PriorityQueue(ar);
+3

Java PriorityQueue O (n) . 6.4 CLSR (. 157 3- ). , siftDown siftUp, , sift, , O (n).

, , , addAll(). adAll() AbstractQueue , O (nlogn).

, O (n) , , Comparator , . @corsiKa . , PriorityQueue, , O (n).

+2

Source: https://habr.com/ru/post/1688621/


All Articles