1079 Total Sales of Supply Chain (25)(25 分)

本文提供了一个使用深度优先搜索(DFS)和广度优先搜索(BFS)算法的示例,通过这两种算法遍历一棵树形结构并计算每个叶子节点的权重值之和。示例中详细展示了如何定义树节点结构、读取输入数据以及实现DFS和BFS的具体过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值