1090 Highest Price in Supply Chain (25 point(s))
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
考察点:图论DFS、树的深度
本质考察树的深度。看到它给出数据的方式,第一反应是直接用找根节点的findRoot()函数的递归次数,可以找到该节点的层次。思路是正确的,但是也果不其然地TLE了。
然后用常规方法,使用DFS,还是采用vector<int>graph[N]建立树,用level[]记录每个结点所在层次,方便在最后计算最深的结点的个数。
也可以用BFS完成。大神链接:https://blog.youkuaiyun.com/richenyunqi/article/details/80146351
第一反应代码(3个用例出现TLE,16分):
#include<iostream>
using namespace std;
const int N = 1e5+7;
int Tree[N];
int cnt,depth = 0;
int findRoot(int x){
cnt++;
if(Tree[x]==-1) return x;
else return findRoot(Tree[x]);
}
int main(void){
int n;double p,rate;
cin>>n>>p>>rate;
for(int i=0;i<n;i++) cin>>Tree[i];
int num = 0;
for(int i=0;i<n;i++){
cnt = 0;
findRoot(i);
if(cnt>depth){
depth=cnt;
num = 1;
}
else if(cnt==depth){
num++;
}
}
for(int i=0;i<depth-1;i++){
p = p *(1.00+0.01*rate);
}
printf("%.2f %d\n",p,num);
return 0;
}
AC代码:
#include<iostream>
#include<vector>
using namespace std;
const int N = 1e5+7;
vector<int> graph[N];
int level[N];
void dfs(int v){
for(int i=0;i<graph[v].size();i++){
int cur = graph[v][i];
level[cur] = level[v]+1;
dfs(cur);
}
}
int main(void){
int n;double p,rate;
cin>>n>>p>>rate;
int a,root;
for(int i=0;i<n;i++){
cin>>a;
if(a==-1) root = i;
else{
graph[a].push_back(i);
}
}
level[root]=0;
dfs(root);
int depth=0,cnt = 0;
for(int i=0;i<n;i++){
if(level[i]>depth){
depth = level[i];
cnt = 1;
}else if(level[i]==depth) cnt++;
}
for(int i=0;i<depth;i++){
p = p *(1.00+0.01*rate);
}
printf("%.2f %d\n",p,cnt);
return 0;
}