PAT甲级-1079 Total Sales of Supply Chain

题目

题目大意

一个供应链由供应商、经销商和零售商组成。给出总节点个数,商品的价格,和利率r%。各节点从0到n-1编号,给出每个节点对应的孩子节点的个数及孩子节点。如果孩子节点个数为0,说明是零售商,给出零售商当前获得的商品数量。求零售商的销售总额。

思路

商品价格随着树深度的增加也随之增加,很明显就是要用dfs求各个零售商的深度。用结构体数组来存储树,然后用dfs根据题意模拟即可。

注意r在计算价格时要* 0.01。

代码

#include <iostream>
#include <vector>
#include <math.h>
using namespace std;

struct node{
    int id;
    vector<int> child;
    int cnt;  // 商品数量,只记录零售商的
};
int n;
double p, r;
vector<node> v;  // 树
double sum = 0;  // 销售总额

void dfs(int root, int num){
    if ((int)v[root].child.size() == 0){
        sum += p * pow(1 + r*0.01, num) * 1.0 * v[root].cnt;
        return;
    }
    for (int i = 0; i < (int)v[root].child.size(); i++){
        dfs(v[root].child[i], num + 1);
    }
}

int main(){
    cin >> n >> p >> r;
    v.resize(n);
    for (int i = 0; i < n; i++){
        int k;
        cin >> k;
        if (k == 0){
            cin >> v[i].cnt;
        }else{
            v[i].child.resize(k);
            for (int j = 0; j < k; j++){
                cin >> v[i].child[j];
            }
        }
    }  // 构建树

    dfs(0, 0);
    printf("%.1lf\n", sum);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_74092648/article/details/142943322