本題基於A1090.
Kj being 0 means that the j-th member is a retailer, then instead the total amount of the product will be given after Kj.
本題讀題要仔細,一開始沒注意到題目有給出零售商賣給用戶的數目,導致沒有思路.
定義結構體比較關鍵:在輸入時便可記錄下每個結點是否爲葉子結點即零售商(用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;
}