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
这里要注意的一个点就是:如果使用递归统计树的深度和各层的结点数,会栈溢出。
代码:
#include <iostream> #include <map> #include <vector> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <queue> using namespace std; map<int,vector<int>> nodes;//记录一颗树 map<int,int> m;//各层对应的结点数 void statistic(int curNode,int depth) {//最坏情况下回递归栈溢出 if(curNode==-1) m[depth]=0; else m[depth]+=1; for(int i=0;i<nodes[curNode].size();++i){ statistic(nodes[curNode][i],depth+1); } } void levelTravel() {//层次遍历求树深度和各层结点数 int depth = 0; queue<int> q; if(!nodes[-1].size()) return ; q.push(nodes[-1][0]); int p = nodes[-1][0]; bool first = true; while(!q.empty()){ int head =q.front(); q.pop(); if(head == p){//开始新一层结点的遍历 ++depth; first = true; } ++m[depth]; for(size_t i=0;i<nodes[head].size();++i){ q.push(nodes[head][i]); if(first) { p = nodes[head][i];//记录depth+1层的第一个结点 first = false; } } } } int main() { int n; double price,rate; cin>>n>>price>>rate; int num; int i=0; int repeat = n; while(repeat--){ cin>>num; nodes[num].push_back(i); ++i; } levelTravel(); double p = price; int count = n; if(m.size()!=0){ map<int,int>::reverse_iterator iter=m.rbegin(); int depth = iter->first; p= price * pow(1+rate/100.0,depth-1); count = iter->second; } /* for(auto iter:m){ cout<<iter.first<<" "<<iter.second<<endl; }*/ printf("%.2lf %d\n",p,count); return 0; } /* 9 1.80 1.00 1 -1 1 1 1 1 1 1 1 */