uva10410(树还原BFS)

思路:根据一棵树的先序和中序还原整棵树,记录每个节点的儿子节点,然后打印出来。

此类题目是比较典型的树还原的考点。不同与二叉树的是,这个可能是多叉树,不能像二叉树那样简单的进行儿子节点的判断。

// #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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值