DFS:递归终点为叶子结点,此时计算乘积
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 1e5 + 10;
struct node {
double p, product;
vector<int>child;
}Node[maxn];
int n;
double p, r;
double ans = 0;
void DFS(int index)
{
if (Node[index].child.size() == 0)
{
ans += Node[index].p*Node[index].product;
return;
}
for (int i = 0; i < Node[index].child.size(); i++)
{
int child = Node[index].child[i];
Node[child].p = Node[index].p*(1 + r);
DFS(child);
}
}
int main()
{
scanf("%d%lf%lf", &n, &p, &r);
r /= 100;
for (int i = 0; i < n; i++)
{
int k;
scanf("%d", &k);
if (k)
{
while (k--)
{
int x;
scanf("%d", &x);
Node[i].child.push_back(x);
}
}
else
{
scanf("%lf", &Node[i].product);
}
}
Node[0].p = p;
DFS(0);
printf("%.1f", ans);
return 0;
}
BFS:队列,分是否为叶子结点操作,不是叶子结点,计算p压进队列,是叶子结点就计算一下乘积
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 1e5 + 10;
struct node {
double p, product;
vector<int>child;
}Node[maxn];
int n;
double p, r;
double ans = 0;
void BFS(int root)
{
queue<int>q;
q.push(root);
while (!q.empty())
{
int top = q.front();
q.pop();
if (Node[top].child.size())
{
for (int i = 0; i < Node[top].child.size(); i++)
{
int child = Node[top].child[i];
Node[child].p = Node[top].p*(1 + r);
q.push(child);
}
}
else ans += Node[top].p*Node[top].product;
}
}
int main()
{
scanf("%d%lf%lf", &n, &p, &r);
r /= 100;
for (int i = 0; i < n; i++)
{
int k;
scanf("%d", &k);
if (k)
{
while (k--)
{
int x;
scanf("%d", &x);
Node[i].child.push_back(x);
}
}
else
{
scanf("%lf", &Node[i].product);
}
}
Node[0].p = p;
BFS(0);
printf("%.1f", ans);
return 0;
}