L2-026 小字辈 (25 分)

这道题是真心简单,天梯选拔赛曾经做过,没做出来,因为当时还没有学数据结构里的图,现在才发现,这道题其实就是一个图题(有向图),只是稍微变了一下图中输入的方式而已。这里我就不再解释为什么是图了,相信提示到这里大家应该能想起来了,就是一个连通有向图,并且从祖宗出发能够遍历到所有节点。
以下给出代码。

#include<iostream>
#include<vector>
#include<queue>
#include<set>
using namespace std;
vector<int> G[100005];
set<int> sc;
int f[100005];
int level[100005];
int inq[100005];
int zu,max1;
void bfs(int s)
{
	queue<int> q;
	q.push(s);
	inq[s]=true;
	while(!q.empty())
	{
		int t=q.front();q.pop();
		if(level[t]>max1)
		{
			max1=level[t];
			sc.clear();
			sc.insert(t);
		}
		else if(level[t]==max1)
		sc.insert(t);
		for(int i=0;i<G[t].size();i++)
		{
			int u=G[t][i];
			if(inq[u]==false)
			{
				inq[u]=true;
				q.push(u);
				level[u]=level[t]+1;
			}
		}
	}
}
int main()
{
	int n;
	cin>>n;
	for(int i=0,a;i<n;i++)
	{
		scanf("%d",&a);
		if(a!=-1)
		G[a].push_back(i+1);
		else
		zu=i+1;
	}
	level[zu]=1;
	bfs(zu);
	cout<<max1<<endl;
	set<int>::iterator it;
	for(it=sc.begin();it!=sc.end();it++)
	{
		if(it!=sc.begin())
		cout<<' ';
		cout<<(*it);
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值