您的位置:首页 > 其它

HDU-1040 as easy as a+b

2011-08-16 21:24 435 查看
其实如果用堆排序来写,这个题就比a+b难!

/*
* HDU-1040 as easy as a+b
* mike-w
* 2011-8-16
* PS: 练习堆排序的题--当然,如果用堆排序做,这就是练习堆排序的题目:p
*/
#include<stdio.h>
#define MAXN 1010

long heap[MAXN];

int swap(long *t1,long *t2)
{
long t3=*t1;
*t1=*t2;
*t2=t3;
return 0;
}

int insert(long e)
{
int n=++heap[0];
heap
=e;
while(n>1&&heap
<heap[n/2])
swap(heap+n,heap+n/2),n/=2;
return 0;
}

long pop(void)
{
long ret=heap[1];
swap(heap+1,heap+heap[0]);
heap[0]--;

long n=1,t=1;
while((t=n<<1)<=*heap)
if(t+1<=*heap && heap[t+1]<heap[t] && heap[t+1]<heap
)
swap(heap+n,heap+t+1),n=t+1;
else if(heap[t]<heap
)
swap(heap+t,heap+n),n=t;
else
break;
return ret;
}

int main(void)
{
int ncase,nnum,i;
long t;

scanf("%d",&ncase);
while(ncase-->0)
{
scanf("%d",&nnum);
for(i=0;i<nnum;i++)
scanf("%ld",&t),insert(t);
for(i=0;i<nnum;i++)
printf("%ld%c",pop(),(i==nnum-1?'\n':' '));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  insert c