复制代码

堆操作

传送门

 

模拟堆

#include <cstdio>
#include <iostream>
using namespace std;

int heap[100005], size = 0;
//第一个元素的下标为1.
void push(int x){
    int i = ++size;
    while(i > 1){
        int p = i / 2;
        if(heap[p] >= x)
            break;
        heap[i] = heap[p];
        i = p;
    }
    heap[i] = x;
}

int pop(){
    //最大值
    int ret = heap[1];
    //要提到根的值
    int x = heap[size--];
    int i = 1;
    while(2 * i + 1 <= size){
        int a = 2 * i, b = 2 * i + 1;
        if(heap[b] > heap[a])
            a = b;
        if(x >= heap[a])
            break;
        heap[i] = heap[a];
        i = a;
    }
    heap[i] = x;
    
    return ret;
}

int main(){
    int n, w;
    char c;
    cin >> n;
    while(n--){
        cin >> c;
        if(c == 'A'){
            cin >> w;
            push(w);
        } else {
            cout << pop() << endl;
        }
    }
    return 0;
}
View Code

优先队列

priority_queue

#include<bits/stdc++.h>
using namespace std;
#define LOACL  freopen("in","r",stdin);\
            freopen("out","w",stdout); 

#define add(u,v,w) (e[++tot]=(edge){v,head[u],1},head[u]=tot;) 
#define f(i,l,r) for(int i=l;i<=r;++i)
#define g(i,l,r) for(int i=l;i>=r;--i)
#define CLR(arr,val) memset(arr,val,sizeof(arr))

typedef long long ll; 
priority_queue<ll> q;
char c;
int n;
ll t ;
int main()
{
    LOACL
    cin>>n;
    f(i,1,n)
    {
        cin>>c;
        if(c=='A')
        {
            cin>>t;
            q.push(t);
        }
        else 
        {
            cout<<q.top()<<endl;
            q.pop();
        }
    }
    return 0;
}
View Code

 

posted @ 2018-03-13 18:14  pg633  阅读(147)  评论(0编辑  收藏  举报