堆【模板】

#include<bits/stdc++.h>
//#include <iostream>
//#include <cstring>
//#pragma GCC optimize(2)
#include<time.h>
using namespace std;
#define maxn 1000005
#define inf 1e18
#define eps 0.00001
typedef long long ll;
const ll mod = 1e9+7;
const double pi = acos(-1);

ll T,key,arr[maxn],num;

void put(ll x)
{
    num++;

    arr[num] = x;

    ll now = num;

    while( now > 1 )
    {

        if(arr[now] < arr[now/2])
            swap(arr[now],arr[now/2]);
        else
            return ;

        now = now/2;
    }
    return ;
}

void pop()
{
    arr[1] = arr[num];
    num--;

    ll now = 1;

    while(now*2 <= num)
    {

        ll a = now*2,b = now*2+1;

        if(arr[now] <= arr[a] && arr[now] <= arr[b])
            return ;

        if( arr[b] < arr[a] )
            a = b;

        swap( arr[now],arr[a] );

        now = a;

    }

    return ;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);

    cin >> T;

    while(T--)
    {
        cin >> key;

        if(key == 1)
        {
            ll x;
            cin >> x;
            put(x);
        }
        else if(key == 2)
        {
            cout << arr[1] << endl;
        }
        else if (key == 3)
        {
            pop();
        }
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/Whyckck/article/details/83659916