n个操作

I: 插入一个数

PM:输出最小值

D k:删除第k个插入的数

C k x:将第k个插入的数的值改成x

DM:删除最小值

 

CODE:

ph[k]:第k个插入的数的下标

hp[i]:下标为i是第k个插入的数

const int N = 100010;

int n, m, h[N], sizee;
int hp[N], ph[N];

void heap_swap(int a, int b)
{
    swap(ph[hp[a]], ph[hp[b]]);
    swap(hp[a], hp[b]);
    swap(h[a], h[b]);
}

void down(int u)
{
    int t = u;
    if (u * 2 <= sizee && h[t] > h[u * 2]) t = u * 2;
    if (u * 2 + 1 <= sizee && h[t] > h[u * 2 + 1]) t = u * 2 + 1;

    if (t != u)
    {
        heap_swap(u, t);
        down(t);
    }
}

void up(int u)
{
    while (u / 2 && h[u] < h[u / 2])
    {
        heap_swap(u, u / 2);
        u /= 2;
    }
}

int main()
{
    cin >> n;

    while (n --)
    {
        char op[5];
        int k, x;
        scanf("%s", op);
        if (!strcmp(op, "I"))
        {
            cin >> x;
            h[++ sizee] = x;
            m ++;
            ph[m] = sizee, hp[sizee] = m;
            up(sizee);
        }
        else if (!strcmp(op, "PM"))
            printf("%d\n", h[1]);
        else if (!strcmp(op, "DM"))
        {
            h[1] = h[sizee --];
            down(1);
        }
        else if (!strcmp(op, "D"))
        {
            cin >> k;
            k = ph[k];
       // Attention! heap_swap(k, sizee);
// 注意要先交换掉 k 和 sizee的信息 sizee--; down(k); up(k); } else { cin >> k >> x; k = ph[k]; h[k] = x; down(k); up(k); } } return 0; }

 

posted @ 2020-11-16 21:06  ctxcc  阅读(106)  评论(0)    收藏  举报