PAT.A1079 Total Sales of Supply Chain

Back to ContentsInsert picture description here

Title

Given a tree with a root number of 0, the price of the goods at the root is p. From the root node to the next layer, the price of the goods will increase by r%, and then give the amount of goods at the leaf nodes. The sum of the price of points.

Sample (can be copied)

10 1.80 1.00
3 2 3 5
1 9
1 4
1 7
0 7
2 6 1
1 8
0 9
0 4
0 3
//output
42.4

important point

  1. Both DFS and BFS can be used for this question. The following wording uses DFS. If you use BFS, you can consider opening two queue <int>, one record number and one record layer.
  2. There are two reasons for recording child nodes using vectors instead of arrays in the node structure of this question: ①vector can dynamically add elements, no need to declare the size, if you use an array, because you do not know the maximum number of child nodes, you need to open a larger space, The memory may overflow. ②Vector automatically modify and record size, no need to use a variable to record the number of children
#include<bits/stdc++.h>
using namespace std;

struct Node{
	double data;
	vector<int> child;
}node[100010];
int n,m,tmp;
double p,r,sum=0; 
void DFS(int root,int depth){
	if(node[root].child.size()==0){
		sum+=node[root].data*pow(1+r,depth);
		return;
	}
	for(int i=0;i<node[root].child.size();i++)DFS(node[root].child[i],depth+1);
}
int main(){
	cin>>n>>p>>r;
	r/=100;
	for(int i=0;i<n;i++){
		scanf("%d",&m);
		if(m==0){
			scanf("%lf",&node[i].data);
		}else{
			while(m--){
				scanf("%d",&tmp);
				node[i].child.push_back(tmp);
			}
		}
	}
	DFS(0,0);
	printf("%.1f\n",p*sum);
    return 0;
}
Published 177 original articles · won praise 5 · Views 6671

Guess you like

Origin blog.csdn.net/a1920993165/article/details/105485822