#include <iostream>
#include <queue>
#include <vector>
#include <string.h>
using namespace std;
queue<int> q;
vector<int> G[1005];
bool vis[1005];
int depth[1005];
int bfs(int L,int start)
{
memset(vis,false,sizeof(vis));
while(!q.empty())
q.pop();
int result=0;
q.push(start);
depth[start]=0;
vis[start]=true;
while(!q.empty())
{
int node = q.front();
q.pop();
if(depth[node]>=L)
continue;
for(int j=0;j<G[node].size();j++)
{
if(vis[G[node][j]]==true)
continue;
q.push(G[node][j]);
depth[G[node][j]]=depth[node]+1;
vis[G[node][j]]=true;
result++;
}
}
return result;
}
int main()
{
int N,L,numOfFollower,followerID,K,id;
scanf("%d%d",&N,&L);
for(int i=1;i<=N;i++)
{
scanf("%d",&numOfFollower);
for(int j=1;j<=numOfFollower;j++)
{
scanf("%d",&followerID);
G[followerID].push_back(i);
}
}
scanf("%d",&K);
for(int i=0;i<K;i++)
{
scanf("%d",&id);
int ans=bfs(L,id);
printf("%d\n",ans);
}
return 0;
}
有一段时间没写广搜了,调试了很久,忘了怎么记录广搜的深度,和同学请教之后就会了。
然后写好提交就过了。
记录广搜的深度:给每一个节点赋予一个深度的属性,在push进队列的时候更新节点的深度为父节点的深度+1.
在取出队列中的节点时,判断深度是否超出要求,若超出,则该节点pop之后continue。