PAT Advanced Level 1079. Total Sales of Supply Chain (25)

博客分析了PAT Advanced Level 1079题目的解决方案,强调在处理树结构问题时,如何避免超时并优化计算节点深度的方法。文章指出直接循环求解深度会导致效率低下,建议使用数组配合输入计算节点深度,并针对特殊情况单独处理,以提高算法性能。
摘要由CSDN通过智能技术生成

【来源】

1079. Total Sales of Supply Chain (25)

【分析】

暂略,有空来填坑。

【代码】

#include <iostream>
#include <vector>
#include <iomanip>
#include <cmath>
#include <cstdio>
using namespace std;

int dep(int node, int* suppliers)
{
    int supply = suppliers[node];
    int depth = 0;
    while (supply != -1){
        supply = suppliers[supply];
        ++depth;
    }
    return depth;
}

int dep2(int node, int* depth, int* suppliers)
{
    int d = depth[node];
    if (d < 0){
        return dep(node, suppliers);
    }
    else{
        return d;
    }
}

int main()
{
    int n;
    double  p, r;
    scanf("%d%lf%lf", &n, &p, &r);

    int* suppliers = new int[n];
    for (int i = 0; i < n; ++i){
        suppliers[i] = -1;
    }
    
    int* products = new int[n];
    for (int i = 0; i < 0; ++i){
        products[i] = 0;
    }

    vector<int> retailors;
    int* depth = new int[n];
    depth[0] = 0;
    for (int i = 1; i < n; ++i){
        depth[i] = -100000;
    }    

    int k;
    for (int i = 0; i < n; ++i){
        scanf("%d", &k);
        if (k != 0){
            int dist;
            for (int j = 0; j < k; ++j){
                scanf("%d", &dist);
                suppliers[dist] = i;
                depth[dist] = depth[i] + 1;
            }
        }
        else{
            retailors.push_back(i);
            int product;
            scanf("%d", &product);
            products[i] = product;
        }
    }

    double total = 0;
    for (int i = 0; i != retailors.size(); ++i){
        int d = dep2(retailors[i], depth, suppliers);
        total += products[retailors[i]] * pow(1 + r/100.0, d);
    }

    printf("%.1lf\n", total*p);

    delete[] suppliers;
    delete[] products;
    system("pause");

    return 0;
}


【点评】

考察树的相关知识,主要是求某一节点的深度信息。注意如果直接写循环求深度,会超时。因此改用数组,在获取输入的时候顺便计算深度值,有问题的节点再另行单独计算,效率会高不少。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值