标签:http io ar for sp cti 代码 on c
题目:UVA10410 - Tree Reconstruction(队列)
题目大意:给出一棵树的BFS和DFS遍历,求这棵数,如果有多种情况输出一种就可以了。
解题思路:利用BFS将DFS串分段,分成一棵一棵子树。然后将子树用队列存储下来,因为先被分出来的子树,在下一层中也是最先被分段。注意:一定要将根节点分离出去,它不属于它的子树。这棵树不一定是二叉树。
代码:
#include <cstdio> #include <queue> #include <vector> using namespace std; const int N = 1005; vector<int> v[N]; struct Seg { int l, r; Seg(int l, int r): l(l), r(r) {} }; queue<Seg> q; int B[N]; int D[N]; int n; void solve () { q.push(Seg(0, n)); int p = 1; int root; while (!q.empty()) { Seg s = q.front(); q.pop(); if (s.r - s.l <= 1 || p == n) continue; root = D[s.l]; int pre = s.l + 1;//分离根节点 for (int i = pre; i < s.r; i++) { if (D[i] == B[p]) { q.push (Seg (pre, i)); v[root].push_back (D[i]); p++; pre = i; } } if (pre < s.r) q.push (Seg (pre, s.r)); } } int main () { int num; while (scanf ("%d", &n) == 1) { for (int i = 0; i < n; i++) scanf ("%d", &B[i]); for (int i = 0; i < n; i++) scanf ("%d", &D[i]); solve(); for (int i = 1; i <= n; i++) { printf ("%d:", i); for (int j = 0; j < v[i].size(); j++) printf (" %d", v[i][j]); printf ("\n"); v[i].clear(); } } return 0; }
UVA10410 - Tree Reconstruction(队列)
标签:http io ar for sp cti 代码 on c
原文地址:http://blog.csdn.net/u012997373/article/details/39203263