A d-tree is a tree of degree d. A complete tree is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right.
Given the pre-order traversal sequence of a complete d-tree, you are supposed to obtain its level-order traversal sequence. And more, for any given node, you must be able to output the bottom-up path from this node to the root.
Input Specification:
Each input file contains one test case. For each case, the first line gives two positive integers: N (≤50) and d (2≤d≤5), which are the total number of nodes in the tree, and the tree's degree, respectively. Then in the next line, N integer keys (≤100) are given as the pre-order traversal sequence of the tree. Finally K (≤N) and K positions are given, where each position is the index of a key in the level-order traversal sequence, starting from 0.
All the numbers in a line are separated by a space.
Output Specification:
For each case, first print in one line the level-order traversal sequence of the complete d-tree. Then for each given position, print in a line the bottom-up path from this node to the root.
All the numbers in a line must be separated by exactly one space, and there must be no extra space at the beginning or the end of the line.
Sample Input:
9 3
91 71 2 34 10 15 55 18 7
3
5 7 3
Sample Output:
91 71 15 7 2 34 10 55 18
34 71 91
55 15 91
7 91
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
const int N = 60;
int n,d,pre[N],p[N],w[N],k;
void dfs(int u,int &k){
w[u] = pre[k++];
for(int i = 1;i<=d;i++){
int c = u*d+i;
if(c<n){
p[c] = u;
dfs(c,k);
}
}
}
void bfs(int u){
cout<<w[0];
for(int i = 1;i<n;i++)cout<<" "<<w[i];
}
vector<int> path;
void to_up(int u){
if(p[u]==-1) return;
path.push_back(w[u]);
to_up(p[u]);
}
int main(){
cin>>n>>d;
for(int i = 0;i<n;i++) cin>>pre[i];
memset(p,-1,sizeof p);
dfs(0,k);
bfs(0);
cout<<endl;
int m;
cin>>m;
while(m--){
path.clear();
int id;cin>>id;
to_up(id);
path.push_back(w[0]);
cout<<path[0];
for(int i = 1;i<path.size();i++)cout<<" "<<path[i];
cout<<endl;
}
}