zoukankan      html  css  js  c++  java
  • 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("
    ");
    	}
    }
    
    
    int main()
    {
    	func();
    }
    

      

  • 相关阅读:
    css子元素水平垂直居中
    js 防抖节流
    NOIP 游记
    flash player播放器用法
    android设备连接不上电脑的解决方法
    AndroidStudio自动下载gradle失败问题解决
    3组Alpha冲刺5/6
    3组Beta冲刺2/5
    3组Beta冲刺5/5
    3组Beta冲刺1/5
  • 原文地址:https://www.cnblogs.com/gk2017/p/7140813.html
Copyright © 2011-2022 走看看