A1090 Highest Price in Supply Chain (25) 树的遍历的一般做法 (采用depth)

本文介绍了一个使用深度优先搜索(DFS)算法解决树结构中寻找最深节点数及对应深度的问题。通过C++实现,代码展示了如何构建树结构、遍历树并计算最深节点的数量和深度。最后,利用输入的初始参数p、r,计算并输出基于最深深度的特定数学表达式结果。

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

建议树相关题目每一题都动手写写,貌似之前也在这个地方栽过,记得先有输入,再做处理,细节问题

#include<cstdio>
#include<iostream>
#include<stack>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=100001;
vector<int> child[maxn];
int maxdepth=-1,num=0;
int n,k,root;
double p,r;
void DFS(int index,int depth)
{
	if(child[index].size()==0)
	{
		if(depth>maxdepth)
		{
			num=1;
		    maxdepth=depth;
		}
		else if(depth==maxdepth)
		{
			num++;
		}
		return;
	}
	for(int i=0;i<child[index].size();i++)
	{
		DFS(child[index][i],depth+1);
	}
}
int main()
{
  cin>>n>>p>>r;
  r=r/100;
  for(int i=0;i<n;i++)
  {
  	scanf("%d",&k);
  	if(k==-1)
  	root=i;
  	else
  	child[k].push_back(i);
  }
  DFS(root,0);
  printf("%.2f %d",p*pow(1+r,maxdepth),num);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值