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;
}


發佈了44 篇原創文章 · 獲贊 9 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章