小字辈(BFS+结构体数组邻接表)

在这里插入图片描述

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
#include <queue> 

using namespace std;

#define MAXN 100005

struct node 
{
    int f;
    int s;
}date;
struct node2
{
    int from;
    int to;
    int w;
    int next;
}edge[MAXN*2];

int N;
int head[MAXN];
int number;
queue<node>q;
bool book[MAXN];
int step = 1;
int ans[MAXN];
int maxs = -1;

void add(int from,int to,int w)
{
    edge[++number].next = head[from]; 
    edge[number].from = from;
    edge[number].to = to;
    edge[number].w = w;
    head[from] = number;
}

int bfs()
{
    int tf,ts;
    
    date.f = -1; //注意:它的根是-1
    date.s = 0;
    
    book[date.f] = true;
    q.push(date);
    while(!q.empty())
    {
        tf = q.front().f;
        ts = q.front().s;
        q.pop();
        for(int j = head[tf];j;j = edge[j].next)
        {
            if(!book[edge[j].to])
            {
                book[edge[j].to] = true;
                date.f = edge[j].to;
                date.s = ts + 1;
                if(date.s>maxs)
                {
                    maxs = date.s;
                    step = 1;
                    ans[step] = date.f;
                }
                else if(date.s==maxs)
                {
                    ans[++step] = date.f;
                }
                q.push(date);
            }
        }
    }
    
    return maxs;
}

int main()
{
    //freopen("test.in","r",stdin);
    //freopen("test.out","w",stdout);
    int i,a;
    scanf("%d",&N);
    for(i = 1;i<=N;i++)
    {
        scanf("%d",&a);
        add(a,i,1);
    }
    
    printf("%d\n",bfs());
    sort(ans+1,ans+1+step);
    for(i = 1;i<=step;i++)
    {
        printf("%d",ans[i]);
        if(i!=step)
            printf(" ");
    }
    
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39592312/article/details/104571689