【模板】【数据结构】堆

1.手写小根堆:

#include <cstdio>
#include <algorithm>
#define maxn 1000003
using namespace std;
int heap[maxn];
int tot=0;
inline void pushup(int x)
{
    for(;x>0;x>>=1) 
    {
        if(heap[x]>heap[x>>1]) break;
        swap(heap[x],heap[x>>1]);
    }
}
inline void pushdown(int x)
{
    for(int y;x<=tot;)
    {
        y=x<<1;
        if(y>tot) break;
        if(heap[y|1]<heap[y]&&y<tot) y|=1;
        if(heap[x]<heap[y]) break;
        swap(heap[x],heap[y]);
        x=y;
    }
}
inline void push(int x)
{
    heap[++tot]=x;
    pushup(tot);
}
inline int top()
{
    return heap[1];
}
inline void pop()
{
    swap(heap[1],heap[tot--]);
    pushdown(1);
}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        int opt,x;
        scanf("%d",&opt);
        switch(opt)
        {
            case 1: {scanf("%d",&x);push(x);break;}
            case 2: {printf("%d\n",top());break;}
            case 3: {pop();break;}
            default:break;
        }
    }
    return 0;
}

2.STL的priority_queue

#include <queue>
using namespace std;
struct node{
    int a,b,c;
    bool operator < (const node &x) const{
        return a.x<x;
    }
};
priority_queue<int>q1;//定义一个整数类型的大根堆
priority_queue<int,vector<int>,greater<int> >q2//定义一个整数类型的小根堆,注意两个尖括号中间一定要加空格,不然容易CE
priority_queue<node>q3;//定义一个node类型的优先队列,node必须重载过小于号。这里的q3是个小根堆
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值