题解 | #【模板】堆#

【模板】堆

https://www.nowcoder.com/practice/13f61c8c92404f5ea5d6fa4c692869fb

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void top(long[] heap, int[] size){
        if (size[0] == 0){
            System.out.println("empty");
        }else{
            System.out.println(heap[0]);
        }
    }

    public static void pop(long[] heap, int[] size){
        if (size[0] == 0){
            System.out.println("empty");
        }else{
            System.out.println(heap[0]);
            heap[0] = heap[size[0]-1] ^ heap[0];
            heap[size[0]-1] = heap[size[0]-1] ^ heap[0];
            heap[0] = heap[size[0]-1] ^ heap[0];
            size[0]--;
            int n = 0;
            while(n < size[0]-1 && n*2+2 <= size[0]-1){
                if (heap[n*2+1] < heap[n*2+2] && heap[n*2+2] > heap[n]){
                    heap[n] = heap[n*2+2] ^ heap[n];
                    heap[n*2+2] = heap[n*2+2] ^ heap[n];
                    heap[n] = heap[n*2+2] ^ heap[n];
                    n = n*2+2;
                }else if (heap[n*2+1] > heap[n*2+2] && heap[n*2+1] > heap[n]){
                    heap[n] = heap[n*2+1] ^ heap[n];
                    heap[n*2+1] = heap[n*2+1] ^ heap[n];
                    heap[n] = heap[n*2+1] ^ heap[n];
                    n = n*2+1;
                }else{
                    break;
                }
            }
            if(n < size[0]-1 && n*2+1 <= size[0]-1 && heap[n*2+1] > heap[n]){
                heap[n] = heap[n*2+1] ^ heap[n];
                heap[n*2+1] = heap[n*2+1] ^ heap[n];
                heap[n] = heap[n*2+1] ^ heap[n];
            }
                        
        }
    }

    public static void push(long[] heap, int[] size, long d){ 
        if (size[0] == 0){
            heap[size[0]++] = d;
        }else{
            heap[size[0]++] = d;

            int n = size[0]-1;
            while(n > 0 && heap[(n-1) / 2] < heap[n]){
                heap[(n-1) / 2] = heap[(n-1) / 2] ^  heap[n];
                heap[n] = heap[(n-1) / 2] ^  heap[n];
                heap[(n-1) / 2] = heap[(n-1) / 2] ^  heap[n];
                n = (n-1) / 2; 
            }
        }
        
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        long d;
        int n = in.nextInt();
        long[] heap = new long[n];    //堆
        int[] size = {0};   //存储堆里面的元素个数
        
        for (int i = 0; i < n; i++){ 
            String a = in.next();
            if (a.equals("push")){
                d = in.nextLong();
                push(heap, size, d);
            }else if (a.equals("top")){
                top(heap, size);
            }else{
                pop(heap, size);
            }

        }
    }
}

全部评论

相关推荐

斑驳不同:还为啥暴躁 假的不骂你骂谁啊
点赞 评论 收藏
分享
有工作后先养猫:太好了,是超时空战警,我们有救了😋
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务