思路:根据一棵树的先序和中序还原整棵树,记录每个节点的儿子节点,然后打印出来。
此类题目是比较典型的树还原的考点。不同与二叉树的是,这个可能是多叉树,不能像二叉树那样简单的进行儿子节点的判断。
// #pragma comment(linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <map>
#include <set>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> ii;
const int inf = 1 << 30;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
inline int Readint(){
char c = getchar();
while(!isdigit(c)) c = getchar();
int x = 0;
while(isdigit(c)){
x = x * 10 + c - '0';
c = getchar();
}
return x;
}
int in[1010],pre[1010];
vector<int> G[1010];
struct line{
int l,r;
};
int n;
void solve(){
queue<line> que;
line tmp,x;
tmp.l=0,tmp.r=n;
que.push(tmp);
int k=1;
while(!que.empty()){
tmp = que.front();
que.pop();
int u=pre[tmp.l];
int top=tmp.l+1;
if (tmp.r-tmp.l<=1) continue;
G[u].push_back(pre[top]);
k++;
int i;
for (i=top+1;i<tmp.r;++i){
if (pre[i]==in[k]){
G[u].push_back(pre[i]);
k++;
x.l=top;
x.r=i;
top=i;
que.push(x);
}
}
if (i==tmp.r){
line x;
x.l=top;
x.r=tmp.r;
que.push(x);
}
}
}
int main()
{
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
while(scanf("%d",&n)!=EOF){
for (int i=1;i<=n;i++)G[i].clear();
for (int i=0;i<n;i++)
scanf("%d",&in[i]);
for (int i=0;i<n;i++)
scanf("%d",&pre[i]);
solve();
for (int i=1;i<=n;i++){
printf("%d:",i);
for (int j=0;j<G[i].size();++j){
printf(" %d",G[i][j]);
}
printf("\n");
}
}
return 0;
}