UVa--548 Tree(二叉树)

来源:互联网 发布:linux 制作iso 编辑:程序博客网 时间:2024/05/21 04:21

UVa 548

题解

根据中序后序序列直接建立(lch[], rch[]),表示结点的左右子节点的权值。

#include <iostream>#include <cstdio>#include <string>#include <sstream>#include <climits>#include <algorithm>using namespace std;const int maxn = 10000 + 10;int inorder[maxn], postorder[maxn], lch[maxn], rch[maxn];int n;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 n > 0;}// inorder[L1..R1], postorder[L2..R2]int build(int L1, int R1, int L2, int R2){    if(L1 > R1) return 0;    int root = postorder[R2];    int p = L1;    while(inorder[p] != root) p++;    int cnt = p - L1;    lch[root] = build(L1, p - 1, L2, L2 + cnt - 1);    rch[root] = build(p + 1, R1, L2 + cnt, R2 - 1);    return root;}int best, best_sum;void dfs(int u, int sum){    sum += u;    if(!lch[u] && !rch[u]){        if(sum < best_sum || (sum == best_sum && u < best)){            best = u;            best_sum = sum;        }    }    if(lch[u]) dfs(lch[u], sum);    if(rch[u]) dfs(rch[u], sum);}int main(){#ifdef LOCALfreopen("data.in", "r", stdin);#endif // LOCAL    while(read(inorder)){        read(postorder);        build(0, n - 1, 0, n - 1);        best_sum = INT_MAX;        dfs(postorder[n - 1], 0);        cout << best << endl;    }    return 0;}
0 0
原创粉丝点击