L2-020 功夫传人 (25分)

本文深入探讨了递归算法的原理与应用,通过具体的C++实现案例,讲解了如何利用递归解决复杂的数据结构问题,如树形结构的遍历与计算。文章通过一个递归函数的实例,详细解释了递归过程中的关键步骤及注意事项。

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

想想是不是因为忘记存值导致结果不对
还有注意理解递归里的return

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
//const int maxn = 100010;
struct node
{
	double data,v,power;
	vector<int> child;
	int leveal;
}Node[maxn];
int n;
double z,r, sum;

void dfs(int index, int leveal)
{
	if(Node[index].data == 0)
	{
		sum += z* pow((1 - r),leveal) * Node[index].power;
		return;
	}
	for(int i = 0; i < Node[index].child.size(); i++)
	{
		dfs(Node[index].child[i], leveal+1);
	}
}

int main()
{
	for(int i = 0; i < maxn; i++)
	{
		Node[i].power = 1;
	}
	cin >> n >> z >>r;
	r = r * 0.01;
	for(int i = 0; i < n; i++)
	{
		int k,x,b;
		cin >> k;
		Node[i].data = k;
		if(k == 0) cin >> Node[i].power;
		else 
		{
			for(int j = 0; j < k; j++)
			{
				cin >> b;
				Node[i].child.push_back(b);
			}
		}
	}
	dfs(0,0);
	cout << (int)sum;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

moumoumouwang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值