PTA 05-树7 堆中的路径 (25分)

题目地址

https://pta.patest.cn/pta/test/15/exam/4/question/713

 

5-5 堆中的路径   (25分)

将一系列给定数字插入一个初始为空的小顶堆H[]。随后对任意给定的下标i,打印从H[i]到根结点的路径。

输入格式:

每组测试第1行包含2个正整数NN和MM(\le 10001000),分别是插入元素的个数、以及需要打印的路径条数。下一行给出区间[-10000, 10000]内的NN个要被插入一个初始为空的小顶堆的整数。最后一行给出MM个下标。

输出格式:

对输入中给出的每个下标i,在一行中输出从H[i]到根结点的路径上的数据。数字间以1个空格分隔,行末不得有多余空格。

输入样例:

5 3
46 23 26 24 10
5 4 3

输出样例:

24 23 10
46 23 10
26 10


/*
评测结果
时间	结果	得分	题目	编译器	用时(ms)	内存(MB)	用户
2017-06-29 14:46	答案正确	25	5-5	gcc	15	1	
测试点结果
测试点	结果	得分/满分	用时(ms)	内存(MB)
测试点1	答案正确	13/13	15	1
测试点2	答案正确	6/6	4	1
测试点3	答案正确	2/2	4	1
测试点4	答案正确	4/4	4	1
*/

/*
此题有坑,数据全拿到之后建堆,虽然堆理论上正确,但会通不过测试
只能读数的时候,读一个然后往堆里插一个 
*/
#include<stdio.h>
int gHeap[1001];

void PrecDown(int index,int A[],int len)
{
	int parent,child;
	int temp=A[index];
	for(parent=index ; parent*2<=len ; parent=child)
	{
		child=parent*2;
		if(child!=len && A[child]>A[child+1])
			child++;
		if (temp<=A[child])
			break;
		else A[parent]=A[child];
	}
	A[parent]=temp;
}

void InsertIntoHeap(int x,int A[],int n)
{
	while( x<A[n/2] && n/2>0)
	{
		A[n]=A[n/2];
		n/=2;
	}
	A[n]=x;
}
void func()
{
	int i,tmp,N,M;
	scanf("%d %d",&N,&M);
	for(i=1;i<=N;i++)
	{
		scanf("%d",&tmp);
		InsertIntoHeap(tmp,gHeap,i);
	}
/*	
	for(i=N/2;i>0;i--)
	{
		PrecDown(i,gHeap,N);
	}
*/	
	for(i=0;i<M;i++)
	{
		scanf("%d",&tmp);
		while(tmp>0)
		{
			printf("%d",gHeap[tmp]);
			if(tmp != 1)
			{
				printf(" ");
			}
			tmp/=2;
		}
		if(i!=M-1)
			printf("\n");
	}
}


int main()
{
	func();
}

  

posted on 2017-07-09 11:11  gravitykey  阅读(462)  评论(0编辑  收藏  举报

导航