您的位置:首页 > 产品设计 > UI/UE

max-Queue(堆)

2016-04-21 14:32 549 查看
【题目描述】

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: