原题:1079. Total Sales of Supply Chain (25)
解题思路:
bfs把每层的价格算出来,遇到叶节点就加入总和即可。
代码如下:
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 100000 + 5;
struct Node
{
double price;
int num;
vector<int> children;
} node[maxn];
int vis[maxn];
double ans;
void bfs(int s, double r, double p)
{
vis[s] = 1;
node[s].price = p;
queue<int> q;
q.push(s);
while(!q.empty())
{
int top = q.front(); q.pop();
if(node[top].children.size() == 0) ans += node[top].num*(node[top].price);
for(int i = 0; i < node[top].children.size(); i++)
{
if(vis[node[top].children[i]]) continue;
node[node[top].children[i]].price = (1.0 + r / 100.0) * node[top].price;
vis[node[top].children[i]] = 1;
q.push(node[top].children[i]);
}
}
}
int main()
{
int n;
double p, r;
while(scanf("%d%lf%lf", &n, &p, &r) == 3)
{
memset(vis, 0, sizeof(vis));
for(int i = 0; i < n; i++) node[i].children.clear();
for(int i = 0; i < n; i++)
{
int k;
scanf("%d", &k);
if(k == 0)
scanf("%d", &node[i].num);
for(int j = 0; j < k; j++)
{
int x;
scanf("%d", &x);
node[i].children.push_back(x);
}
}
ans = 0;
bfs(0, r, p);
printf("%.1f\n", ans);
}
return 0;
}