首页 > 代码库 > UVA - 10410 Tree Reconstruction
UVA - 10410 Tree Reconstruction
Description
You have just finished a compiler design homework question where you had to find the parse tree of an expression. Unfortunately you left your assignment in the library, but luckily your friend picked it up for you. Instead of e-mailing you the parse tree so that you can rewrite the solution, your friend decides to play a practical joke and sends you just the DFS and BFS trace. Rather than try to redo the entire question you decide to reconstruct the tree.
Input
The input file contains several test cases as described below.
The first line of a input is the number n (1 <= n <= 1000) of nodes in the tree. The nodes in the tree are numbered 1, 2, ...,n. The remaining numbers are the BFS traversal followed by theDFS traversal. Note that when a parent was expanded the children were traversed in ascending order.
Output
The output for each case should consist of n lines, one for each node. Each line should start with the node number followed by a colon followed by a list of children in ascending order. If there is more than one solution, any correct answer is acceptable.
Sample Input
8 4 3 5 1 2 8 7 6 4 3 1 7 2 6 5 8
Sample Output
1: 7 2: 6 3: 1 2 4: 3 5 5: 8 6: 7: 8:
题意:告诉你DFS和BFS的结果,求树
思路:从DFS入手,每次枚举它之后的点有没有可能是它的子节点,判断从BFS判断,首先深度要是+1的,还有就是两个之间必须都要是访问多的才行
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> #include <vector> using namespace std; const int MAXN = 1010; int n, ord[MAXN], dfs[MAXN], bfs[MAXN], deep[MAXN]; vector<int> arr[MAXN]; queue<int> q; int vis[MAXN]; int check(int a, int b, int curDeep) { int e = dfs[a]; int f = dfs[b]; int c = ord[e]; int d = ord[f]; for (int i = a+1; i < b; i++) { int tmp = dfs[i]; if (deep[tmp] == 0) continue; if (deep[tmp] != curDeep) return 0; } for (int i = c+1; i < d; i++) { int tmp = bfs[i]; if (!vis[tmp]) return 0; } return 1; } void cal(int cur, int curDeep) { int cnt = dfs[cur]; for (int i = cur+1; i < n; i++) { int tmp = dfs[i]; if (vis[tmp]) continue; if (check(cur, i, curDeep+1)) arr[cnt].push_back(tmp); else continue; q.push(i); vis[tmp] = 1; deep[tmp] = curDeep + 1; } } void print() { for (int i = 1; i <= n; i++) { printf("%d:", i); for (int j = 0; j < arr[i].size(); j++) printf(" %d", arr[i][j]); printf("\n"); } } int main() { while (scanf("%d", &n) != EOF) { memset(vis, 0, sizeof(vis)); memset(deep, 0, sizeof(deep)); memset(ord, 0, sizeof(ord)); memset(dfs, 0, sizeof(dfs)); memset(bfs, 0, sizeof(bfs)); for (int i = 0; i <= n; i++) arr[i].clear(); while (!q.empty()) q.pop(); for (int i = 0; i < n; i++) { int t; scanf("%d", &t); bfs[i] = t; ord[t] = i; } for (int i = 0; i < n; i++) scanf("%d", &dfs[i]); deep[dfs[0]] = 1; q.push(0); while (!q.empty()) { int cnt = q.front(); q.pop(); cal(cnt, deep[dfs[cnt]]); } print(); } return 0; }