# max-Queue（堆）

16 篇文章 0 订阅

【题目描述】

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
评论
08-19 987
03-12 247
04-18 187
03-07 79
07-29 5494
09-13 417
07-16 373
05-18 439
04-17 639
02-08 3167
01-16 1750
09-23 312

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