1. 程式人生 > >1090 Highest Price in Supply Chain (25 分)【dfs】

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;
}