Java手写堆为什么后面5个样例全部t了
查看原帖
Java手写堆为什么后面5个样例全部t了
363355
yateng楼主2022/3/25 16:41
import java.util.List;
import java.util.Scanner;

public class Main {
    static final int mx = (int) (1e6+10);
    //二叉堆
    static int [] heap = new int[mx];
    //堆的节点个数
    static int tot = 0;

    public static void add(int x)
    {
        heap[++tot] = x;
        int chd=tot;
        for(int fa=tot>>1;fa>=1;fa>>=1)
        {
            if(heap[fa]>heap[chd]){
                int t=heap[fa];
                heap[fa]=heap[chd];
                heap[chd]=t;
            }else
                break;
            chd=fa;
        }
    }

    public static void dequeue(){
        heap[1]=heap[tot--];

        for(int fa=1;fa<<1 <=tot;)
        {
            int t;
            int chd = fa<<1;
            if((chd|1)<=tot)
            {
                if(heap[chd]>heap[chd|1]){
                    chd=chd|1;
                }
            }
            if(heap[chd]<heap[fa]){
                t=heap[chd];
                heap[chd]=heap[fa];
                heap[fa]=t;
                fa=chd;
            }else
                break;
        }
    }


    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Integer op ;
        int n = 0;
        n = in.nextInt();
        for(int i=1;i<=n;i++)
        {
            op = in.nextInt();
            if(op == 1)
            {
                op = in.nextInt();
                add(op);
            }else if(op == 2)
            {
                System.out.println(heap[1]);
            }else{
                dequeue();
            }
        }
    }
}
2022/3/25 16:41
加载中...