A1079

本题基于A1090.
K​j being 0 means that the j-th member is a retailer, then instead the total amount of the product will be given after K​j.
​​本题读题要仔细,一开始没注意到题目有给出零售商卖给用户的数目,导致没有思路.
定义结构体比较关键:在输入时便可记录下每个结点是否为叶子结点即零售商(用bool型flag存储),若为零售商,则将其贩卖数量存储在amount中.层次layer可通过之后BFS遍历时更新.
这样一来,在BFS中一旦遇到flag=true的,则可直接将贩卖总额加到总额中去(利用amount,layer即指数,r+0.01即底数,p算出)最后将返回值返回出去.
但DFS简便很多,见DFS代码段.

BFS

#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=100010;
struct node{
	vector<int> child;
	bool flag;
	double amount;
	double layer;
}nodes[maxn];
double BFS(int root,double p,double r){
	nodes[root].layer=0;
	double total=0;
	queue<int> q;
	q.push(root);
	while(!q.empty()){
		int now=q.front();
		q.pop();
		if(nodes[now].flag){
			double lay=nodes[now].layer;
			total+=p*pow(1+r*0.01,lay)*nodes[now].amount;
		}else{
			for(int i=0;i<nodes[now].child.size();i++){
				int temp=nodes[now].child[i];
				nodes[temp].layer=nodes[now].layer+1;
				q.push(temp);
			}
		}
	}
	return total;
}
int main(){
	#ifdef ONLINE_JUDGE
	#else
		freopen("1.txt","r",stdin);
	#endif
	int n,number;
	double p,r;
	scanf("%d %lf %lf",&n,&p,&r);
	for(int i=0;i<n;i++){
		scanf("%d",&number);
		if(number==0){
			nodes[i].flag=true;
			scanf("%lf",&nodes[i].amount);
		}else{
			for(int j=0;j<number;j++){
				int k;
				scanf("%d",&k);
				nodes[i].child.push_back(k);
			}
			nodes[i].flag=false;
		}
	}
	double total_sales=BFS(0,p,r);
	printf("%.1f\n",total_sales);
	return 0;
}

DFS:

#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=100010;
double total=0,p,r;;
struct node{
	vector<int> child;
	double amount;
}nodes[maxn];
void DFS(int idx,int layer){
	if(nodes[idx].child.size()==0){
		total+=p*pow(1+r*0.01,double(layer))*nodes[idx].amount;
		return;
	}
	for(int i=0;i<nodes[idx].child.size();i++){
		DFS(nodes[idx].child[i],layer+1);
	}
}
int main(){
	#ifdef ONLINE_JUDGE
	#else
		freopen("1.txt","r",stdin);
	#endif
	int n,number;
	scanf("%d %lf %lf",&n,&p,&r);
	for(int i=0;i<n;i++){
		scanf("%d",&number);
		if(number==0){
			scanf("%lf",&nodes[i].amount);
		}else{
			for(int j=0;j<number;j++){
				int k;
				scanf("%d",&k);
				nodes[i].child.push_back(k);
			}
		}
	}
	DFS(0,0);
	printf("%.1f\n",total);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章