例题6-8 UVA548 树 Tree

难度:4

目前第一道难度为4的题,感觉属于里面算简单的了,处理一下输入,然后建树,然后dfs,dfs的过程中记录一下,最后到叶子的时候和预先设置好的值比较一下,就可以了,逻辑和算法笔记上面最短路那里一模一样,第一优先级,如果这个路径的和最小,那就选这个路径的叶子,第二优先级,如果这个路径的和和最小的一样,但是这个路径的叶子最小,那就选这个叶子。

#include <bits/stdc++.h>

#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()

using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pa;

struct node {
    int data;
    node *lchild, *rchild;
};

int min1, min2;
vi in, post;
map<int, int> mp;

vi solve(string s) {
    vi v;
    stringstream ss(s);
    string temp;
    while (ss >> temp) {
        v.pb(stoi(temp));
    }
    return v;
}

node* create(int postl, int postr, int inl, int inr) {
    if (postl > postr) return NULL;
    node* root = new node;
    root->data = post[postr];
    int k = mp[post[postr]];
    int numleft = k - inl;
    root->lchild = create(postl, postl + numleft - 1, inl, k - 1);
    root->rchild = create(postl + numleft, postr - 1, k + 1, inr);
    return root;
}

void dfs(node* root, int sum) {
    if (root->lchild == NULL && root->rchild == NULL) {
        if (sum + root->data < min1) {
            min1 = sum + root->data;
            min2 = root->data;
        } else if (sum + root->data == min1 && root->data < min2) {
            min2 = root->data;
        }
        return;
    }
    if (root->lchild != NULL) dfs(root->lchild, sum + root->data);
    if (root->rchild != NULL) dfs(root->rchild, sum + root->data);
}

int main() {
    string s1, s2;
    while (getline(cin, s1) && getline(cin, s2)) {
        min1 = 100000000;
        min2 = 100000000;
        mp.clear();
        in = solve(s1);
        post = solve(s2);
        for (int i = 0; i < (int) in.size(); i++) {
            mp[in[i]] = i;
        }
        node* root = create(0, (int) in.size() - 1, 0, (int) in.size() - 1);
        dfs(root, 0);
        cout << min2 << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值