YbtOj例题:二叉堆3 龙珠游戏

STL优先队列写法

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int n,ne[N];
struct node{
    int val,pos;
    bool operator < (const node &G) const
    {
        return val<G.val;
    }
}a[N];
bool used[N];
priority_queue<node> q;
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i].val);
        a[i].pos=i;
        ne[i]=i+1;
        if(i!=n) q.push(a[i]);
    }
    int cnt=0;
    while(cnt<n)
    {
        node tmp=q.top();
        while(used[tmp.pos]) 
        {
            q.pop();
            tmp=q.top();
        }
        while(used[ne[tmp.pos]]) ne[tmp.pos]=ne[ne[tmp.pos]];
        if(ne[tmp.pos]>n) 
        {
            q.pop();
            tmp=q.top();
        }
        else
        {
            cnt+=2;
            printf("%d %d ",tmp.val,a[ne[tmp.pos]].val);
            used[tmp.pos]=true;used[ne[tmp.pos]]=true;
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/smartljy/p/13548260.html