1. 程式人生 > >PAT (Advanced Level) 1079 Total Sales of Supply Chain (樹的層序遍歷)

PAT (Advanced Level) 1079 Total Sales of Supply Chain (樹的層序遍歷)

 簡單的層序遍歷題,層序掃一遍整棵樹,每層個數統計下最後計算即可。

#include<bits/stdc++.h>
using namespace std;


int n;
double p, r;
vector<int> t[100005];
int mark[100005];
int level[100005];
int max_level;

void solve(){
	memset(level,0,sizeof(level));
	max_level = 0;
	int front = 0, rear = 1, cnt = 0;
	queue<int> q;
	q.push(0);
	while(!q.empty()){
		int x = q.front();
		q.pop();
		++front;
		if(t[x].size() > 0){
			for(int i = 0; i < t[x].size(); ++i){
				q.push(t[x][i]);
				++cnt;
			}
		}
		else{
			level[max_level] += mark[x];
		}
		if(front == rear){
			rear += cnt;
			cnt = 0;
			++max_level;
		}
	}
	double res = 0;
	for(int i = 0; i < max_level; ++i){
//		printf("%d ",level[i]);
		res += level[i] * pow(1+r,i);
	}
	printf("%.1lf",res*p);
}

int main(){
	memset(mark,0,sizeof(mark));
	scanf("%d%lf%lf",&n,&p,&r);
	r = r/100;
	int k, x;
	for(int i = 0; i < n; ++i){
		scanf("%d",&k);
		if(k){
			for(int j = 0; j < k; ++j){
				scanf("%d",&x);
				t[i].push_back(x);
			}
		}
		else{
			scanf("%d",&mark[i]);			
		}
	}
	solve();
	return 0;
}