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和BFS都能达到效果,这里选择了DFS,在对每条分支进行遍历时,要判断需要不需要更新最大深度,最后根据最大深度来进行求解。这里有几个要注意的地方,一是数据p和r最好用double,用float有的测试点会出错。第二就是输入数据的时候,要找出根节点的编号,还有题目给出的是结点与结点的父节点之间的关系,不要弄错了。
代码:
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 100010;
int n,Depth=0,max_depth=0,num=0;
double p, r;
struct node {
int layer;
vector<int>child;
}Node[maxn];
void DFS(int index, int depth) {
if (Node[index].child.size() == 0) {
if (depth > max_depth)
{
max_depth = depth;
num = 1;
}
else if (depth == max_depth) {
num++;
}
return;
}
for (int i = 0; i < Node[index].child.size(); i++)
{
int child = Node[index].child[i];
DFS(child, depth + 1);
}
}
int main()
{
int father,root;
scanf("%d%lf%lf", &n, &p, &r);
for (int i = 0; i < n; i++)
{
scanf("%d", &father);
if (father == -1)//之前发生了段错误,因为不存在Node[-1]的结点,这里要用if-else,而不能只用if
{
root = i;
}
else {
Node[father].child.push_back(i);
}
}
DFS(root, 0);
double ans = p;//这里一定要用double,用float由于精度问题会出错
for (int i = 0; i < max_depth; i++)
{
ans = ans * (1 + r * 0.01);
}
printf("%.2f %d\n", ans,num);
/*
#include<algorithm>
ans=p*pow(1+r,max_depth);
*/
return 0;
}