【ACM】- PAT. A1079 Total Sales of Supply Chain【树的遍历】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26398495/article/details/81809855
题目链接
题目分析

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

解题思路

1、树的 静态存储 ,边输入边建树;
2、先序遍历,记录当前结点深度,到达叶结点时累加即可;


AC程序(C++)
/**************************
*@Author: 3stone
*@ACM: PAT.A1079 Total Sales of Supply Chain
*@Time: 18/7/30
*@IDE: VSCode 2018 + clang++
***************************/
#include<cstdio>
#include<cstring>
#include<vector>
#include<cmath>

using namespace std;

const int maxn = 100010;

int n;
double p, r, total_sales;

//树结点
struct Node{
    vector<int> child;
    double value;
}node[maxn];


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

    if(node[root].child.size() == 0){ //叶节点
        total_sales += (p * pow(r + 1, depth) * node[root].value); 
        return;
    }
    for(int i = 0; i < node[root].child.size(); i++){
        pre_order(node[root].child[i], depth + 1);
    }
}

int main() {

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

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

        //获取结点信息
        int temp_num, temp;
        for(int i = 0; i < n; i++) {
            scanf("%d", &temp_num);
            if(temp_num == 0) {  //叶节点
                scanf("%lf", &node[i].value);
            }
            else { //非叶节点
                for(int j = 0; j < temp_num; j++) {
                    scanf("%d", &temp);
                    node[i].child.push_back(temp);
                }
            }
        }

        //先根遍历
        pre_order(0, 0); //初始层次

        printf("%.1f\n", total_sales);

    }//while-scanf

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_26398495/article/details/81809855