此题解决了我对堆操作的两个疑惑:
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;
}