习题6-11 树重建(Tree Reconstruction, UVa 10410)

看了有一晚了。。也看了别人的题解。。还是感觉不太清楚。。。。

先占个坑,下边是一种做法。。还有根据bfs来分割dfs的做法。。。

update 10.9 
去学习了下树的栈遍历,回来感觉能明白这种做法了。
题意即为确定各节点的父子关系,从dfs序中,很显然的,一路下去都是前驱节点的孩子。
只是如何判断此时这一子树已经访问结束呢?
很显然从bfs序中来寻找答案,bfs[u] + 1 < bfs[v]即为子节点。
那么等于1的情况呢?
bfs[u] + 1 == bfs[v]时,u为root必然成立,否则当v < u时可以当做成立。

#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <algorithm>
#include <sstream>
#include <utility>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <cctype>
#define CLEAR(a, b) memset(a, b, sizeof(a))
#define IN() freopen("in.txt", "r", stdin)
#define OUT() freopen("out.txt", "w", stdout)
#define LL long long
#define maxn 10005
#define maxm 100005
#define mod 1000000007
#define INF 1000000007
#define eps 1e-5
#define PI 3.1415926535898
#define N 26
using namespace std;
//-------------------------CHC------------------------------//
vector<int> son[maxn];
int bfs[maxn];

int main() {
	int n;
	while (~scanf("%d", &n)) {
		for (int i = 1, x; i <= n; ++i)
			scanf("%d", &x), bfs[x] = i, son[i].clear();
		int root;
		scanf("%d", &root);
		stack<int> sta;
		sta.push(root);
		for (int i = 1, x; i < n; ++i) {
			scanf("%d", &x);
			for (;;) {
				int u = sta.top();
				if (bfs[u] + 1 < bfs[x] || u == root) {
					son[u].push_back(x);
					sta.push(x);
					break;
				}
				else sta.pop();
			}
		}
		for (int i = 1; i <= n; ++i) {
			printf("%d:", i);
			for (int j = 0, sz = son[i].size(); j < sz; ++j)
				printf(" %d", son[i][j]);
			puts("");
		}
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值