【ACM】- PAT. A1090 Highest Price in Supply Chain 【树的遍历】

12 篇文章 0 订阅
题目链接
题目分析

1、用树来表示商品分销,每个结点代表一个人,计算最高出售价,即叶节点的最大权值;
2、每增加一层,加价r%
3、结点编号0 ~ N-1;上限10^5;结果保留2位小数;
4、输入是每个结点的父节点,根节点的父节点为-1

解题思路

1、由于只需记录结点关系,结点自身不带信息,直接用树的 静态存储 的简化形式vector<int>[]即可;
2、要计算最高价格,实际就是求出最深叶结点,再根据深度计算即可。


AC程序(C++)
/**************************
*@Author: 3stone
*@ACM: PAT.A1090 Highest Price in Supply Chain
*@Time: 18/8/17
*@IDE: VSCode 2018 + clang++
***************************/
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<cmath>

using namespace std;

const int maxn = 100010;

int n, max_num, max_depth;
double p, r;

//树结点
vector<int> child[maxn];

//先根遍历(DFS)
void pre_order(int root, int depth) {

    if(child[root].size() == 0){ //叶节点

        if(depth == max_depth) max_num++;
        else if(depth > max_depth) {
            max_depth = depth;
            max_num = 1;
        }
        return;
    }
    for(int i = 0; i < child[root].size(); i++){
        pre_order(child[root][i], depth + 1);
    }
}

int main() {

    while(scanf("%d %lf %lf", &n, &p, &r) != EOF) {

        //初始化
        for(int i = 0; i <= n; i++){
            child[i].clear();
        }
        max_depth = 0;
        max_num = 0;
        r /= 100;   //r%

        //获取结点信息
        int farther, root_key;
        for(int i = 0; i < n; i++) {
            scanf("%d", &farther);
            if(farther == -1) {  //根节点
                root_key = i;
            }
            else {
                child[farther].push_back(i);
            }
        }

        //先根遍历
        pre_order(root_key, 0); //求出最大深度即可

        printf("%.2f %d\n", p * pow(r + 1, max_depth), max_num);

    }//while-scanf

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值