We can build Binary Heaps by two methods, the first is to insert items one by one from the input; the second is to build a random binary tree all together from the input at first and then adjust the tree to a binary heap. (As described in book P.140)
Give a sequence of distinct integer to build two binary heaps in those two ways, and output the nodes on level order of each tree.
输入格式:
2 lines
The first line means the number of sequence. This number is not limited
The second line gives the sequence of distinct integer. The integers are divided by comma. You must build the heap according to the input order.
输出格式:
2 lines
Two lines of sequence of numbers divided by comma. The numbers represent the nodes on the heap by level order. The first line is the result by inserting items one by one. The second is by building the tree all together and then adjusting.
输入样例:
在这里给出一组输入。例如:
5
3,5,4,2,1
输出样例:
在这里给出相应的输出。例如:
1,2,4,5,3
1,2,4,3,5
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int HeapDataType;
typedef struct Heap
{
HeapDataType* a;
int size;
int capacity;
}HP;
void AdjustUp(HeapDataType* a, int child);
void HeapPush(HP* ph, HeapDataType n);
void HeapPrint(HP* ph);
void HeapInit(HP* ph);
void downshift(int* a,int cur,int n);
void HeapPush(HP* ph, HeapDataType n)
{
if (ph->size == ph->capacity)
{
ph->capacity = ph->capacity == 0 ? 4 : ph->capacity * 2;
HeapDataType* tmp = (HeapDataType*)realloc(ph->a, sizeof(HeapDataType) * ph->capacity);
if (NULL == tmp)
{
printf("realloc fail\n");
exit(-1);
}
ph->a = tmp;
}
ph->a[ph->size] = n;
ph->size++;
}
void HeapPrint(HP* ph)
{
int i = 0;
for (i = 0; i < (ph->size)-1; i++)
{
printf("%d,", ph->a[i]);
}
printf("%d",ph->a[i]);
printf("\n");
}
void HeapInit(HP* ph)
{
ph->a = NULL;
ph->capacity = ph->size = 0;
}
void Swap(HeapDataType* e1, HeapDataType* e2)
{
int tmp = *e1;
*e1 = *e2;
*e2 = tmp;
}
void AdjustUp(HeapDataType* a, int child)
{
int parent = (child - 1) / 2;
while (child > 0)
{
if (a[child] < a[parent])
{
Swap(&a[child], &a[parent]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
void downshift(int* a,int cur,int n)
{
int child=cur*2+1;
while(child<n){
if(child+1<n&&a[child+1]<a[child])
{
child++;
}
if(a[child]<a[cur]){
Swap(&a[child],&a[cur]);
cur=child;
child=cur*2+1;
}
else
break;
}
}
int main()
{
int n,i;
char c;
scanf("%d",&n);
int a[n];
scanf("%d",&a[0]);
for(i=1;i<n;i++)
{
scanf("%c",&c);
scanf("%d",&a[i]);
}
HP* hp1;hp1=(HP*)malloc(sizeof(HP));HeapInit(hp1);
HP* hp2;hp2=(HP*)malloc(sizeof(HP));HeapInit(hp2);
for (i=0;i<n;i++)
{
HeapPush(hp1,a[i]);
AdjustUp(hp1->a, hp1->size - 1);
HeapPush(hp2,a[i]);
}
HeapPrint(hp1);
for(i=(n-2)/2;i>=0;i--)
downshift(hp2->a,i,n);
HeapPrint(hp2);
return 0;
}