标签:c++
题目链接:
一共两种操作 放入和取出(MAX)的
最多有10W次操作 ,暴力肯定会超时。
我们可以将盒子理解为一个大顶堆,即父节点大于左右子节点。
1.每次放入糖果时往上维护堆
2.取出时模仿堆排序的算法 将根节点(max)输出并与最后一个节点交换 再维护堆
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int q[100005];
void HeapAdjust(int loc,int len)
{
int pos=loc,leftchild=2*loc,rightchild=2*loc+1;
if(loc<=len/2)
{
if(leftchild<=len&&q[leftchild]>q[pos])
pos=leftchild;
if(rightchild<=len&&q[rightchild]>q[pos])
pos=rightchild;
if(pos!=loc)
{
swap(q[pos],q[loc]);
HeapAdjust(pos,len);
}
}
return;
}
int main()
{
int n,len=0,b;
char a;
scanf("%d",&n);
getchar();
for(int j=1;j<=n;j++)
{
cin>>a;
if(a=='A')
{
scanf("%d",&q[++len]);
int l=len/2;
while(l!=0) //依次往上维护堆
{
HeapAdjust(l,len);
l=l/2;
}
getchar();
}
else if(a=='T')
{
printf("%d\n",q[1]);
swap(q[1],q[len--]);
HeapAdjust(1,len); //维护
}
}
return 0;
}
标签:c++
原文地址:http://blog.csdn.net/axuan_k/article/details/43191003