05-树6. Path in a Heap (25) 小根堆

05-树6. Path in a Heap (25)

Time Limit: 20 Sec  Memory Limit: 256 MB

题目连接

http://www.patest.cn/contests/mooc-ds2015spring/05-%E6%A0%916

Description

Insert a sequence of given numbers into an initially empty min-heap H. Then for any given index i, you are supposed to print the path from H[i] to the root.

 

Input

Each input file contains one test case. For each case, the first line gives two positive integers N and M (<=1000) which are the size of the input sequence, and the number of indices to be checked, respectively. Given in the next line are the N integers in [-10000, 10000] which are supposed to be inserted into an initially empty min-heap. Finally in the last line, M indices are given.

Output

For each index i in the input, print in one line the numbers visited along the path from H[i] to the root of the heap. The numbers are separated by a space, and there must be no extra space at the end of the line.

 

Sample Input

5 3 46 23 26 24 10 5 4 3

Sample Output

24 23 10 46 23 10 26 10

HINT

 

题意

 

题解:

随便拿个数组模拟一下小根堆就好了……

代码:

 

//qscqesze
#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <typeinfo>
#include <fstream>
#include <map>
#include <stack>
typedef long long ll;
using namespace std;
//freopen("D.in","r",stdin);
//freopen("D.out","w",stdout);
#define sspeed ios_base::sync_with_stdio(0);cin.tie(0)
#define test freopen("test.txt","r",stdin)  
#define maxn 200001
#define mod 10007
#define eps 1e-9
int Num;
char CH[20];
//const int inf=0x7fffffff;   //нчоч╢С
const int inf=0x3f3f3f3f;
/*

inline void P(int x)
{
    Num=0;if(!x){putchar('0');puts("");return;}
    while(x>0)CH[++Num]=x%10,x/=10;
    while(Num)putchar(CH[Num--]+48);
    puts("");
}
*/
inline ll read()
{
    ll x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
inline void P(int x)
{
    Num=0;if(!x){putchar('0');puts("");return;}
    while(x>0)CH[++Num]=x%10,x/=10;
    while(Num)putchar(CH[Num--]+48);
    puts("");
}
//**************************************************************************************
int a[maxn];
int main()
{
    //test;
    int n=read(),m=read();
    for(int i=1;i<=n;i++)
    {
        a[i]=read();
        int tmp=i;
        while(tmp!=1&&a[tmp]<a[tmp/2])
        {
            swap(a[tmp],a[tmp/2]);
            tmp/=2;
        }
    }
    for(int i=1;i<=m;i++)
    {
        int first=1;
        int x=read();
        while(x!=0)
        {
            if(first)
                printf("%d",a[x]),first=0;
            else
                printf(" %d",a[x]);
            x/=2;
        }
        printf("\n");
    }
}

 

posted @ 2015-05-25 21:27  qscqesze  阅读(244)  评论(0编辑  收藏  举报