Argus 堆

此题解决了我对堆操作的两个疑惑:

1、cmp()决定大根堆还是小根堆

2、元素的add操作

#include <string.h>
#include <stdio.h>
#define maxn 10005
struct node{
	int id;
	int Time;
}in[maxn];
node stack[maxn];
int heaplength;
int pere(int i){
	return (int)i/2;
}
int lch(int i){   
	return i<<1; 
}
int rch(int i){  
	return (i<<1)+1;
}
int cmp(node a,node b)
{
	if(a.Time!=b.Time)
		return a.Time-b.Time;
	return a.id-b.id;	
}
void exchange(int x,int y)
{
	node t=in[x];
	in[x]=in[y];
	in[y]=t;
}
void maxHeapify(int i,int heapsize)
{
     int l=lch(i);
     int r=rch(i);
    // printf("...%d %d...\n",l,r);
     int largest;
     if(l<=heapsize && cmp(in[l],in[i])>0)
     	largest=l;
	 else
	 	largest=i;
	 if(r<=heapsize && cmp(in[r],in[largest])>0)
	 	largest=r;
	 
	 if(largest != i)
	 {
		//printf("<<%d>>\n",i);
	 	exchange(i,largest);
		maxHeapify(largest,heapsize);
	 }				     
}
void del(int idx)
{
	exchange(idx,heaplength);	
	heaplength--;
	maxHeapify(1,heaplength);
	
}
int add(node x)
{
	int idx;
	if(heaplength==maxn-1){
		if(cmp(x,in[1])>0)
			return 0;
		else del(1);
	}	
	heaplength++;
	idx=heaplength;
	in[idx]=x;
	while (idx > 1)
    {
        if (cmp(in[idx],in[pere(idx)]) > 0){ 
			exchange(idx,pere(idx)); 
			idx = pere(idx);
		 }
        else break;
    } 
	return 1;

}
int main()
{
	freopen("in.txt","r",stdin);
	freopen("out.txt","w",stdout);
	int k,i,number,id,Time;
	node t;
	char str[10];
	heaplength=0;
	while(scanf("%s",str))
	{
		if(str[0]=='#')
			break;
		scanf("%d %d",&id,&Time);
		for(i=1;i<maxn;i++)
		{
			t.id=id;t.Time=Time*i;
			if(add(t)==0)	break;		
		}
		
	}	
	scanf("%d",&k);
	int temp = heaplength;
	int top=1;
    for (i = 1; i <=temp; i++)
    {
        stack[top++] = in[1];
        del(1);
    }
    //printf("<<%d>>\n",temp);
    for (i = 0; i < k; i++) 
		printf("%d\n", stack[--top].id);
		
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值