PAT A1090 Highest Price in Supply Chain 供應鏈中的最大價格[樹的遍歷 深度優先]
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.
一個供應鏈是由零售商,經銷商和供應商(任何一個參與到商品從供應者到顧客過程中的人)組成的網路。
從一個根源供應商開始,供應鏈上的每一個人從它的供應者那裡以P價格買入商品然後以r%的增長率賣給其他人。假設供應鏈中的每個成員只有一個供應者,也沒有供應迴路。
Input Specification:
Each input file contains one test case. For each case, The first line contains three positive numbers: N (≤10^5), 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. S root for the root supplier is defined to be −1. All the numbers in a line are separated by a space.
第一行包含三個正整數 N(供應鏈中的成員總數) P(根源供應者給出的商品價格) r(價格增長率)
下一行包含N個數字,每一個數字Si 是第i個成員的供應者編號,根源供應者的供應者編號定為-1.
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 1010.
打印出我們可以從零售商那裡得到的最高價格,保留2位有效數字。以及有幾個零售商以這個價格賣出。兩個數字之間有空格隔開。
思路:即構造出供應樹,找到最深的幾個結點。
#include<cstdio>
#include<cmath>
#include<vector>
using namespace std;
const int maxn = 100010;
vector<int> child[maxn];
double p,r;
int n,maxDepth=0,num=0;//maxDepth為最大深度,num為最大深度的葉結點個數
//深度優先搜尋
void DFS(int index,int depth){
//尋找最大深度並計數
if(child[index].size()==0){
if(depth>maxDepth){
maxDepth = depth;
num=1;
}else if(depth==maxDepth){
num++;
}
return;
}
for(int i=0;i<child[index].size();i++){
DFS(child[index][i],depth+1);
}
}
int main(){
int father,root;
scanf("%d%lf%lf",&n,&p,&r);
r /=100;
for(int i=0;i<n;i++){
scanf("%d",&father);
if(father!=-1){
child[father].push_back(i);
}else{
root=i;
}
}
DFS(root,0);
printf("%.2f %d\n",p*pow(1+r,maxDepth),num);
return 0;
}