Tree Reconstruction UVA - 10410

本文介绍了一种使用广度优先搜索(BFS)和深度优先搜索(DFS)来构建树形结构的方法。通过记录每个节点的位置,并利用栈来辅助处理节点间的父子关系,最终输出树的结构。此方法不仅适用于二叉树,还能用于生成更复杂的树结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用数组,首先记录BFS时每个节点的位置,然后利用栈,首先压入根节点的位置,对于后面读取的每个节点,如果是当前节点的子节点,那么位置之差至少为2(只考虑这种简单的情况,因为题目当中指出只要输出正确的情况之一即可),或者栈顶所表示的节点是根节点,那么就可以忽略位置的差值。同时注意,产生的树不一定必须是二叉树。具体实现见如下代码:

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
using namespace std;

int main(){
	int n;
	while (cin >> n){
		int bfs[1010];
		int dfs[1010];
		vector<int> res[1010];
		int root = 0;
		for (int i = 1; i <= n; i++){
			int x;
			cin >> x;
			bfs[x] = i;
		}
		cin >> root;
		stack<int> s;
		s.push(root);
		for (int i = 1; i < n; i++){
			int x;
			cin >> x;
			while (true){
				int a = s.top();
				if (a == root || bfs[x] > bfs[a] + 1){
					s.push(x);
					res[a].push_back(x);
					break;
				}
				else s.pop();
			}
		}
		for (int i = 1; i <= n; i++){
			cout << i << ":";
			for (int j = 0; j < res[i].size(); j++){
				cout << " " << res[i][j];
			}
			cout << endl;
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值