题目链接
题目描述
A supply chain is a network of retailers(零售商), distributors(经销商), and suppliers(供应商)-- everyone involved in moving a product from supplier to customer.Starting from one root supplier, everyone on the chain buys products from one’s supplier in a price P and sell or distribute them in a price that is r% higher than P. It is assumed that each member in the supply chain has exactly one supplier except the root supplier, and there is no supply cycle.Now given a supply chain, you are supposed to tell the highest price we can expect from some retailers.
Input Specification:
Each input file contains one test case. For each case, The first line contains three positive numbers: N (≤), the total number of the members in the supply chain (and hence they are numbered from 0 to N−1); P, the price given by the root supplier; and r, the percentage rate of price increment for each distributor or retailer. Then the next line contains N numbers, each number Si is the index of the supplier for the i-th member. Sroot for the root supplier is defined to be −1. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the highest price we can expect from some retailers, accurate up to 2 decimal places, and the number of retailers that sell at the highest price. There must be one space between the two numbers. It is guaranteed that the price will not exceed .
Sample Input:
9 1.80 1.00
1 5 4 4 -1 4 5 3 6
Sample Output:
1.85 2
题目解法
1.第一行给出了人数n,初始价格price,以及增长率 r%,每经过一个商家则价格上涨r%
2.第二行相当于从左到右,从序号为0到n-1的商家的“上家”(也就是经销商)的编号,如果该值为-1则表示该序号的商家是供应商,题目阐述了供应商只有一个且不存在环,所以可以抽象为树,由于直接建树(指针)不方便,我们可以用书的静态写法,涉及到树的遍历时,PAT也很喜欢考这个,一定要掌握。
3.本题需要求最高的价格,也就是树的深度,以及拿到最高价格的零售商的个数,也就是在此深度的结点个数。
代码
#include<cstdio>
#include<vector>
#include<cmath>
using namespace std;
const int maxn=100010;
vector<int> children[maxn];//静态写法
int n,maxdepth=0,num=0;
double price,r;
void dfs(int root,int depth){
if(children[root].size()==0){//到达叶节点时,更新树的深度
if(depth>maxdepth){
maxdepth=depth;
num=1;
}else if(depth==maxdepth) num++;
return;
}
for(int i=0;i<children[root].size();i++){
dfs(children[root][i],depth+1);
}
}
int main(){
int temp,root;
scanf("%d %lf %lf",&n,&price,&r);
for(int i=0;i<n;i++){
scanf("%d",&temp);
if(temp!=-1){
children[temp].push_back(i);
}else{
root=i;
}
}
dfs(root,0);
printf("%.2f %d\n",price*pow(1+r*0.01,maxdepth),num);
return 0;
}