#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
using namespace std;
const int maxn = 1010;
int G[maxn][maxn] = { 0 }; //邻接矩阵
bool isVisited[maxn] = { false };
int layers[maxn] = { 0 }; //记录每个节点的层次
int N, L; //N为节点个数
void BFS(int s, int& ans) { //s为入口节点
if (isVisited[s] == true)
return;
queue<int>q; //定义队列
q.push(s);
isVisited[s] = true; //是否已进入队列
while (!q.empty())
{
int tmp = q.front();
int layer = layers[tmp];
q.pop();
for (int i = 1; i <= N; i++) {
if (G[tmp][i] != 0 && isVisited[i] == false) { //可达且未访问
isVisited[i] = true;
layers[i] = layer + 1;
ans++;
if (layers[i] == L + 1) {
ans--;
return;
}
q.push(i);
}
}
}
return;
}
int main() {
scanf("%d %d", &N, &L);
int m, n;
for (int i = 1; i <= N; i++) { //有向图
scanf("%d", &m);
for (int j = 0; j < m; j++) {
scanf("%d", &n);
G[n][i] = 1;
}
}
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%d", &n);
int ans = 0;
BFS(n, ans);
printf("%d\n", ans);
//恢复原样layers和isVisited
memset(layers, 0, sizeof(int) * maxn);
memset(isVisited, 0, sizeof(bool) * maxn);
}
}
PTA 1076 Forwards on Weibo
最新推荐文章于 2024-09-04 21:39:45 发布