比较直接的一道题,注意存储数组G时要反向存储即可。
#include <stdio.h>
#include <queue>
using namespace std;
struct node {
int v, layout;
};
const int MAXN = 1010;
int N, L, G[MAXN][MAXN] = {0};
int BFS(node Node) {
int ans = 0;
queue<node> q;
bool inq[MAXN] = {false};
q.push(Node);
inq[Node.v] = true;
while (!q.empty()) {
for (int i = 1; i <= N; ++i) {
if (G[q.front().v][i] != 0&&!inq[i] && q.front().layout + 1 <= L) {
q.push(node{i, q.front().layout + 1});
inq[i] = true;
ans++;
}
}
q.pop();
}
return ans;
}
int main() {
int checkNum, temp;
scanf("%d%d", &N, &L);
for (int i = 1; i <= N; ++i) {
int num;
scanf("%d", &num);
for (int j = 0; j < num; ++j) {
scanf("%d", &temp);
G[temp][i] = 1;
}
}
scanf("%d", &checkNum);
for (int i = 0; i < checkNum; ++i) {
scanf("%d", &temp);
printf("%d\n", BFS(node{temp, 0}));
}
return 0;
}