HDU-1040 堆排序

唉,HDU-1280 我已经WA若干次,仍未AC,于是做一道堆排序的题缓解一下情绪。

在作此题的过程中,我又复习了一个被我忽视的C语言特性,函数的参数的计算顺序是从右向左的。不过貌似HDU上的编译器从左到右==!所以对于这些不确定的特性我还是不用为好。

/*
 * hdu-1040
 * mike-w
 * 2012-4-14
 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_SIZE 1024
#define HEAP_SIZE 2048
#define LC(X) (2*(X))
#define RC(X) (2*(X)+1)
#ifndef true
#define true 1
#endif

int heap[HEAP_SIZE];
int N,T;

int swap(int *e1, int *e2)
{
	int tmp=*e1;
	*e1=*e2;
	*e2=tmp;
	return 0;
}

int heap_in(int e)
{
	if(heap[0]==HEAP_SIZE)
		return -1;
	heap[++heap[0]]=e;
	int x=heap[0];
	int p=x/2;
	while(p>0 && heap[p]>heap[x])
		swap(heap+p,heap+x),x=p,p/=2;
	return 0;
}

int heap_out(void)
{
	if(heap[0]==0)
		return -1;
	int ret=heap[1];
	swap(heap+1,heap+heap[0]);
	heap[0]--;
	int p=1,x;
	int lc,rc;
	while(true)
	{
		lc=LC(p);
		rc=RC(p);
		x=p;
		if(lc<=heap[0] && heap[lc]<heap[x])
			x=lc;
		if(rc<=heap[0] && heap[rc]<heap[x])
			x=rc;
		if(x==p)
			break;
		swap(heap+x,heap+p);
		p=x;
	}
	return ret;
}

int main(void)
{
#ifndef ONLINE_JUDGE
	freopen("in","r",stdin);
#endif
	int e;
	scanf("%d",&T);
	while(T-->0)
	{
		heap[0]=0;
		scanf("%d",&N);
		while(N-->0)
			scanf("%d",&e), heap_in(e);
		while(heap[0]>0)
			printf("%d",heap_out()),putchar(heap[0]==0?'\n':' '); /* 注意副作用 */
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值