1090 Highest Price in Supply Chain (25 分)(樹的遍歷)
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 (<=105), 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 1010.
Sample Input:
9 1.80 1.00
1 5 4 4 -1 4 5 3 6
Sample Output:
1.85 2
題目大意:
給一棵樹,在樹根處貨物的價格為p,然後每往下走一層,價格增加r%,求所有葉子結點的最高價格,以及這個價格的葉子結點個數~
分析:
用二維陣列v[i][j]儲存,對於每一個結點i,它的孩子結點的下標push_back儲存在v[i]中。用深度優先搜尋dfs,儲存當前結點的下標index以及當前結點所在層數,當 當前結點的孩子結點個數為0的時候說明是葉子結點,更新maxdepth和maxnum的值,最後輸出~
注意:
如果採用儲存某個結點的父結點的下標的形式,然後一直遍歷到根結點的深度/廣度優先,會出現三個超時。因為從葉子結點往上遍歷將會把所有路徑都走一遍,很多都是重複走的路徑,會超時,沒有從根結點往下遍歷的方式快~~
記得r是百分比,要除以100之後再計算複利~
原文連結:https://blog.csdn.net/liuchuo/article/details/52206430
題解
子結點:0 1 2 3 4 5 6 7 8
父結點:1 5 4 4 -1 4 5 3 6
#include <bits/stdc++.h>
using namespace std;
const int maxn=100010;
vector<int> child[maxn];
double p,r;
int n,maxDepth=0,num=0;
void DFS(int index,int depth){
if(child[index].size()==0){ //到達葉節點
if(depth>maxDepth){ //深度比最大深度大
maxDepth=depth; //更新最大深度
num=1; //重置最大深度的葉節點個數為1
}else if(depth==maxDepth){ //深度等於最大深度
num++; //最大深度的葉節點個數加1
}
return;
}
for(int i=0;i<child[index].size();i++)
DFS(child[index][i],depth+1); //遞迴訪問結點index的子結點
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif
int father,root;
cin>>n>>p>>r;
r/=100;
for(int i=0;i<n;i++){
cin>>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;
}
本文來自部落格園,作者:勇往直前的力量,轉載請註明原文連結:https://www.cnblogs.com/moonlight1999/p/15768735.html