自己的解法:(感觉做得很乱,改了很长时间,一直因为层数的设定出错)
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 1010;
struct Node
{
vector<int> f;
int level;
Node()
{
level = 0;
}
}node[maxn];
queue<int> q;
bool inq[maxn] = { 0 };
int n, k,c;
void bfs(int v)
{
for (int i = 1; i <= n; i++)
{
node[i].level = 0;
}
memset(inq, 0, sizeof(inq));
inq[v] = 1;
q.push(v);
c = 0;
while (!q.empty())
{
int v = q.front();
q.pop();
if (node[v].level < k) {
for (int i = 0; i < node[v].f.size(); i++)
{
if (inq[node[v].f[i]] == 0)
{
c++;
q.push(node[v].f[i]);
node[node[v].f[i]].level = node[v].level+1;
inq[node[v].f[i]] = 1;
}
}
}
}
printf("%d\n", c);
}
int main()
{
int num, temp,query;
scanf("%d %d", &n, &k);
for (int i = 1; i <= n; i++)
{
scanf("%d", &num);
for (int j = 1; j <= num; j++)
{
scanf("%d", &temp);
node[temp].f.push_back(i);
}
}
scanf("%d", &query);
for (int i = 0; i < query; i++)
{
scanf("%d", &temp);
bfs(temp);
}
return 0;
}