洛谷p3378堆模板题

来源:互联网 发布:软件开发安全管理规范 编辑:程序博客网 时间:2024/05/16 15:53

https://www.luogu.org/problemnew/show/P3378
没用stl

#include<bits/stdc++.h>using namespace std;int n,heap[1000001];int heap_size=0;void put(int d){    int now,next;    heap[++heap_size]=d;    now=heap_size;    while(now>1){        next=now>>1;        if(heap[now]>=heap[next]) break;        swap(heap[now],heap[next]);        now=next;    }}int get(){//heap[1]为堆顶    int now=1,next,res=heap[1];    heap[1]=heap[heap_size--];    while(now*2<=heap_size)    {        next=now*2;        if(next<heap_size&&heap[next+1]<heap[next]) next++;        if(heap[now]<=heap[next]) break;        swap(heap[now],heap[next]);        now=next;        }           return res;}int main(){    cin>>n;    while(n--)    {        int t;        cin>>t;        if(t==1)        {            int x;            cin>>x;            put(x);        }        else if(t==2)        {            cout<<heap[1]<<endl;        }        else{            get();        }    }}
原创粉丝点击