Acwing---839. 模拟堆-3.代码实现

时间:2024-02-19 18:38:25


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.Buffer;
import java.util.Scanner;

public class _839模拟堆 {
    static int N = 100010;
    static int[] h = new int[N];//h代表heap(堆)

    static int[] ph = new int[N];//ph(point->heap)可以获得第几个插入的元素现在在堆的那个位置

    static int[] hp = new int[N]; //hp(heap->point)可以获得在堆的第n个元素存的是第几个插入的元素
    static int size, m;

    static void heap_swap(int a, int b) {//交换在heap中位置分别为a,b的两个元素
        swap(ph, hp[a], hp[b]);//第一步交换蓝色线
        swap(hp, a, b);//绿线
        swap(h, a, b);//真实值
    }

    static private void swap(int[] arr, int a, int b) {
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }

    private static void down(int u) {//当前堆的元素下沉
        int min = u;
        if (u * 2 <= size && h[u * 2] < h[min]) min = u * 2;
        if (u * 2 + 1 <= size && h[u * 2 + 1] < h[min]) min = u * 2 + 1;
        if (u != min) {
            heap_swap(min, u);
            down(min);
        }
    }

    private static void up(int u) {
        while (u / 2 > 0 && h[u / 2] > h[u]) {
            heap_swap(u / 2, u);
            u /= 2;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        while (n-- > 0) {
            String[] s = br.readLine().split(" ");
            String opt = s[0];
            if (opt.equals("I")) {
                int x = Integer.parseInt(s[1]);
                size++;
                m++;
                h[size] = x;
                ph[m] = size;
                hp[size] = m;
                up(size);
            } else if (opt.equals("PM")) System.out.println(h[1]);
            else if (opt.equals("DM")) {
                heap_swap(1, size);
                size--;
                down(1);
            } else if (opt.equals("D")) {
                int k = Integer.parseInt(s[1]);
                int u = ph[k];
                heap_swap(u, size);
                size--;
                down(u);
                up(u);
            } else if (opt.equals("C")) {
                int k = Integer.parseInt(s[1]);
                int x = Integer.parseInt(s[2]);
                int u = ph[k];
                h[u] = x;
                down(u);
                up(u);
            }
        }
    }
}