PAT A 1090. Highest Price in Supply Chain (25)

题目

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

 

实际上就是求树的最大深度问题。

只需根据每个id的供应商(即父节点)构建树,dfs即可。

 

代码:

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

struct test_point	//深度探测用点
{
	int id;
	double price;
	test_point(int i=0,double p=0.0):id(i),price(p){}
};

int main()
{
	int n;
	double p,r;
	cin>>n>>p>>r;

	int root,tempi;	//根的id,临时数据
	vector<vector<int>> child(n);	//各个成员的孩子(即供应链的下家)
	for(int i=0;i<n;i++)
	{
		scanf("%d",&tempi);
		if(tempi!=-1)
			child[tempi].push_back(i);
		else
			root=i;
	}

	double max_price=p;	//最高价格
	int count=0;	//最高价格计数
	vector<test_point> stack;	//dfs用堆栈
	test_point tp1,tp2;
	stack.push_back(test_point(root,p));	//压入根节点
	while(!stack.empty())	//dfs
	{
		tp1=stack.back();
		stack.pop_back();
		if(tp1.price>max_price)	//刷新价格
		{
			max_price=tp1.price;
			count=1;
		}
		else if(tp1.price==max_price)
			count++;
		if(!child[tp1.id].empty())	//压入子成员
		{
			tp1.price*=(100.0+r)/100.0;
			for(int i=0;i<child[tp1.id].size();i++)
			{
				tp2.price=tp1.price;
				tp2.id=child[tp1.id][i];
				stack.push_back(tp2);
			}
		}
	}

	printf("%.2lf %d", max_price,count);

	return 0;
}


 

 

 

 

你可能感兴趣的:(C++,算法,pat)