UVA548 Tree(树)

本题vjudge链接

  • 给你二叉树的中序和先序遍历,让你求从根节点到叶节点的的距离权值和最小,如果有多解,叶节点的权值要小,输出叶节点的权值
#include <bits/stdc++.h>

using namespace std;

const int M = 1e4 + 10;
string str;
int ino[M], posto[M], ans, Max, lson[M], rson[M], len = 0;

void dfs(int u, int sum) {
    if (!lson[u] && !rson[u]) {
        if (sum < Max || (sum == Max && ans > u)) {
            ans = u, Max = sum;
        }
    }
    if (lson[u] != 0) dfs(lson[u], sum + lson[u]);
    if (rson[u] != 0) dfs(rson[u], sum + rson[u]);
}

int build(int a, int b, int c, int d) {
    if (c > d) return 0;
    int v = posto[b], indx = c;
    while (ino[indx] != v && indx <= d) indx++;
    int l = indx - c;
    lson[v] = build(a, a + l - 1, c, indx - 1);
    rson[v] = build(a + l, b - 1, indx + 1, d);
    return v;
}

void init(int *A) {
    char *s = &str[0];
    len = 0;
    while (1) {
        sscanf(s, "%d", A + len++);
        if (strchr(s, ' ') == nullptr) return;
        s = strchr(s, ' ') + 1;
    }
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
#endif
    while (getline(cin, str)) {
        init(ino);
        getline(cin, str);
        init(posto);
        build(0, len - 1, 0, len - 1);
        ans = Max = 1e5;
        dfs(posto[len - 1], posto[len - 1]);
        printf("%d\n", ans);

        memset(lson, 0, sizeof lson);
        memset(rson, 0, sizeof rson);
    }
    return 0;
}

原地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值