PAT甲1076. Forwards on Weibo (30)

#include <cstdio>
#include <cstdlib>
#include <map>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
using namespace std;

const int maxn=1100;
int N,L,C,check;
vector<int> G[maxn];
bool vis[maxn]={false};
int lay[maxn]={0};

int BFS(int x)
{
    queue<int> q;
    q.push(x);
    int num=0;
    lay[x]=0;
    vis[x]=true;
    while(!q.empty())
    {
            int top=q.front();
            q.pop();
            if(lay[top]<=L)
            {
                num++;
            }
            else break;
            for(int i=0;i<G[top].size();i++)
            {
                if(vis[G[top][i]]==false)
                {
                    q.push(G[top][i]);
                    vis[G[top][i]]=true;
                    lay[G[top][i]]=lay[top]+1;
                }
            }

    }
    return num;
}

int main()
{
    scanf("%d%d",&N,&L);
    for(int i=1;i<=N;i++)
    {
        int k;
        scanf("%d",&k);
        for(int j=0;j<k;j++)
        {
            int user;
            scanf("%d",&user);
            G[user].push_back(i);
        }
    }
    scanf("%d",&C);
    for(int i=0;i<C;i++)
    {
        for(int j=1;j<=N;j++)
        {
            vis[j]=false;
        }
        scanf("%d",&check);
        int num=BFS(check);
        printf("%d\n",num-1);
    }
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yhy489275918/article/details/80229919