首页 > 其他 > 详细

hihocoder 1105 题外话·堆 堆的应用

时间:2015-01-27 11:17:31      阅读:271      评论:0      收藏:0      [点我收藏+]

题目链接:

1105







一共两种操作 放入和取出(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;
}






hihocoder 1105 题外话·堆 堆的应用

原文:http://blog.csdn.net/axuan_k/article/details/43191003

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!