UVa 548 Tree 根据后序遍历和中序遍历建树后DFS

来源:互联网 发布:万得股票软件mac版本 编辑:程序博客网 时间:2024/05/22 01:41




#include <cstdio>#include <cstring>#include <iostream>#include <cstdlib>#include <sstream>#include <algorithm>#define PAUSE system("pause")using namespace std;const int maxv = 10000 + 10;//lch和rch分别记录当前节点的左右子树的根节点int in_order[maxv], post_order[maxv], lch[maxv], rch[maxv];int n, ans, pos;bool read(int *a) {string line;if (!getline(cin, line)) return false;stringstream ss(line);int x;n = 0;while (ss >> x) a[n++] = x;  //流化输入return true;}//inorder [L1, R1], postorder [L2, R2]int build(int L1, int R1, int L2, int R2) {if (L1 > R1) return 0; //空树返回0int root = post_order[R2];int p = L1;while (in_order[p] != root) p++; //debugint cnt = p - L1; //左子树长度lch[root] = build(L1, L1 + cnt - 1, L2, L2 + cnt - 1);rch[root] = build(p + 1, R1, L2 + cnt, R2 - 1);return root;}void dfs(int root, int sum) {sum += root;if (!lch[root] && !rch[root]) {if (sum < ans || (sum == ans && root < pos)) {ans = sum;pos = root;}return;}if (lch[root]) dfs(lch[root], sum); //debug if(lch[root])if (rch[root]) dfs(rch[root], sum); //debug if(rch[root])}int main(){while (read(in_order)) {read(post_order);int root = build(0, n - 1, 0, n - 1);ans = pos = 0x7fffffff;dfs(root, 0);printf("%d\n", pos);}return 0;}






0 0
原创粉丝点击