L2-026 小字辈 (25 分)

这篇博客探讨了如何通过深度优先搜索算法(DFS)来解决计算机科学中树的最大深度计算问题。在分析过程中,博客作者强调了理解题目要求的重要性,并提供了相应的代码实现。
摘要由CSDN通过智能技术生成

 本题思路:读完题目之后,应该知道这道题求得是树的深度,同时记录深度最大时的孩子。用深搜即可。

下面是代码:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<vector<int>>man;
vector<int>small;
int sign;
int result = 0;
void dfs(int j,int cnt) {
	if (result < cnt&&man[j].size() == 0) {
		result = cnt;
		small.clear();		//因为找到了比当前更深的,所以要清空之前的数据.
	}
	if (result == cnt)
		small.push_back(j);
	for (int i = 0; i < man[j].size(); i++) {
		dfs(man[j][i],cnt+1);
	}
}
int main() {
	int num;
	cin >> num;
	man.resize(num+1);
	for (int i = 1; i <= num; i++) {
		int tmep;
		cin >> tmep;
		if (tmep == -1) {
			sign = i;
			continue;
		}
		man[tmep].push_back(i);
	}
	dfs(sign, 1);
	cout << result << endl;
	sort(small.begin(), small.end());
	for (int i = 0; i < small.size(); i++) {
		if (i != 0)
			cout << " ";
		cout << small[i];
	}
	system("pause");
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值