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 (<=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 S~i~ 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.
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 10^10^.
Sample Input:
9 1.80 1.00
1 5 4 4 -1 4 5 3 6
Sample Output:1.85 2
题目大意:给出一个数组a[i] = j; 表示i的供应商是j, 当a[i]=-1的时候,表示i是最顶端的供应商。求供应链的最长长度,以及处于最长长度供应链末端零售商的人数
对给出的数据做以下处理:建立一个二维vector向量,chain[i]表示i为供应商,chain[i][j]表示j的供应商是i。chain[i].size()=0 则表示i是零售商
maxdepth记录供应链的最长长度,cnt记录处于最长供应链末端零售商的人数。
这一题其实就是用数组建立树,并遍历树的过程。从顶端供应商root开始遍历,直到遍历到零售商为止(即chain[i].size()=0); 遍历过程中,如果发现当前的depth比maxdepth大,则更新maxd,并更新cnt=1;
若遍历过程中发现当前depth=maxdepth则更新cnt的值;
注意点:计算最高价格的时候,要用double类型, 用float类型,会有一些测试点不能通过,应该是溢出导致
在dfs()遍历树的时候,不能调用dfs(index, depth++), 应该用dfs(index, depth+1); 前者会改变同意层次循环中的depth值导致最终结果错误
#include<iostream> #include<vector> #include<cmath> using namespace std; int cnt=0, maxdepth=0; double ans=0.0; vector<vector<int>> chain; void dfs(int index, int depth){ if(chain[index].size()==0){ if(depth>maxdepth){maxdepth=depth; cnt=1;} else if(depth==maxdepth) cnt++; return; } for(int i=0; i<chain[index].size(); i++) dfs(chain[index][i], depth+1); } int main(){ int n, i, root, temp; double p, r; cin>>n>>p>>r; chain.resize(n); for(i=0; i<n; i++){ cin>>temp; if(temp==-1){root=i; continue;} chain[temp].push_back(i); } dfs(root, 0); printf("%.2f %d", p*pow((1.0+r/100.0), maxdepth), cnt); return 0; }