ZOJ 2724 二叉堆的插入与删除

STL

#include<iostream>
#include<queue>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

struct node
{
    char s[100];
    int pri,idx;
    friend bool operator <(node a,node b){
        return a.pri>b.pri;
    }
};

int main()
{
    char str[1000];
    priority_queue<node> q;
    while(scanf("%s",str)!=EOF){
        if(strcmp(str,"GET")==0){
            if(q.empty())
                printf("EMPTY QUEUE!\n");
            else{
                node tmp=q.top();
                q.pop();
                printf("%s %d\n",tmp.s,tmp.idx);
            }
        }
        else if(strcmp(str,"PUT")==0){
            char ss[100];
            int p;int x;
            scanf("%s%d%d",ss,&p,&x);
            node tmp;
            strcpy(tmp.s,ss);
            tmp.idx=p;
            tmp.pri=x;
            q.push(tmp);
        }
    }
    return 0;
}

二叉树

#include<iostream>
#include<queue>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

const int maxn=60000+10;
const int maxs=100;

struct info
{
    char name[maxs];
    int para;   //参数
    int pri,t;  //优先级,顺序。
}p[maxn];

int heap[maxn];
int top,used;

int compare(int a,int b)
{
    if(p[a].pri<p[b].pri)
        return -1;
    if(p[a].pri>p[b].pri)
        return 1;
    if(p[a].t>p[b].t)
        return 1;
    if(p[a].t<p[b].t)
        return -1;
    return 0;
}

int main()
{
    int used=0,top=0;
    int cnt=0;
    char str[1000];
    while(scanf("%s",str)!=EOF){
        if(strcmp(str,"GET")==0){
            if(top){
                printf("%s %d\n",p[heap[1]].name,p[heap[1]].para);
                int k=1;
                heap[k]=heap[top--];
                while(k*2<=top){
                    int t=2*k;
                    if(t<top&&compare(heap[t],heap[t+1])>0)
                        t++;
                    if(compare(heap[k],heap[t])>0){
                        swap(heap[k],heap[t]);
                        k=t;
                    }else
                        break;
                }
            }
            else
                printf("EMPTY QUEUE!\n");

        }else{
            scanf("%s%d%d",p[used].name,&p[used].para,&p[used].pri);
            p[used].t=cnt++;
            int k=++top;
            heap[k]=used++;
            while(k>1){             //从下往上建堆。
                int t=k/2;
                if(compare(heap[k],heap[t])<0){
                    swap(heap[k],heap[t]);
                    k=t;
                }
                else
                    break;
            }
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值