max-Queue(堆)

【题目描述】

Use a max-Heap to design a priority queue with integer value. Each element stores an integer. The larger the integer is, the higher the priority of the element is.

【题目输入】

The first line contains the total number of test cases.
For each test case, the first line has 2 numbers. The first one is the initial size of the queue, n. The second is the number of operation, m. The second line contains n integers, which are the initial elements. You should store them in the priority queue.
In the next m lines, each line represent an operation. 'I' indicates an insertion with an integer. 'P' denotes removing top element of the queue. We assume that the queue will never be empty.
1 <= n <= 100

2
3 4
2 1 3
I 4
I 5
P
P
4 4
10 8 9 12
I 1
I 20
P
P
【题目输出】

Output the top element after each operation.

4
5
4
3
12
20
12
10
【我的程序】

#include <iostream>
#define maxSize 150
using namespace std;

int num, a[maxSize];

void swapOp(int x, int y)
{
    int temp=a[x]; a[x]=a[y]; a[y]=temp;
}

void downOp(int x)
{
    while (x*2<=num)
    {
        x*=2;
        if (x+1<=num && a[x+1]>a[x]) x++;
        if (a[x]>a[x/2]) swapOp(x,x/2); else break;
    }
}

void upOp(int x)
{
    while (x/2>=1){ if (a[x]>a[x/2]) swapOp(x,x/2); else break; x/=2; }
}

int main()
{
    int n,m,cas;

    cin>> cas;
    for (int j=0; j<cas; j++)
    {
        cin>> n>> m;  num=n;
        for (int i=1;i<=n;i++) cin>>a[i];
        for (int i=n/2; i>=1; i--) downOp(i);

        char ch;
        for (int i=0; i<m; i++)
        {
            cin>> ch;
            if (ch=='P'){ swapOp(1,num); num--; downOp(1); cout<< a[1]<< endl;}
            else{ cin>>a[++num]; upOp(num); cout<< a[1]<< endl; }
        }
    }

    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值