1090 Highest Price in Supply Chain (25 分)【dfs】

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

题意:有n个供应商,根供应商的价格是P,分发到子节点供应商要多出百分之r, 问供应商最高的卖价是多少?输入n个供应商,下标从0到n-1,表示第i个成员的供应商索引号,-1的是根供应商

9 1.80 1.00
1 5 4 4 -1 4 5 3 6
//0  1  2  3  4  5  6  7  8
//1  5  4  4 -1  4  5  3  6
//第0个成员的供应商是1,第1个成员的供应商是5,第2个成员的供应商是4,依此类推

解题思路:实质上就是树的遍历(最多有多少层)。输入数据处理:用二维数组保存父节点与子节点,如果是子节点,就v[father].push_back(i),如果是-1,就是根节点。深度搜索:从根节点往下深搜,当到达叶子节点,如果层次比maxdepth大就换,如果相等就maxnum++,不是叶子节点就继续对子节点进行深搜,子节点深搜就要当前节点的depth再加一。

#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;

int maxdepth,maxnum,n;
vector<int>v[100010];//犯了一个非常低级的错误:定义数组大小应是固定数字而不能是变量
void dfs(int root,int depth)
{
	if(v[root].size()==0)
	{
		if(maxdepth==depth)
		{
			maxnum++;
		}
		else if(maxdepth<depth){
			maxdepth=depth;
			maxnum=1;
		}
	}
	for(int i=0;i<v[root].size();i++)
	{
		dfs(v[root][i],depth+1);
	}
}

int main(void) 
{
	int root;
	double p,r;
	scanf("%d %lf %lf",&n,&p,&r);

	for(int i=0;i<n;i++)
	{
		int father;
		scanf("%d",&father);
		if(father==-1) root=i;
		else v[father].push_back(i);
	}
	dfs(root,0);
	double maxp=p;
	for(int i=1;i<=maxdepth;i++)
	{
		maxp*=(1+0.01*r);
	}
	printf("%.2lf %d",maxp,maxnum);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Imagirl1/article/details/85851870