[PAT] A1076 Forwards on Weibo
(重要!)
BFS遍历图
详见算法笔记第363页
AC代码
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
#define MAX 1002
struct node {
int v;
int level;
};
vector<node>Adj[MAX];
bool inq[MAX] = { false };
int n, maxLevel;
int numQuery;
int BFS(int s) {
int numZF = 0;
queue<node>q;
node start;
start.v = s;
start.level = 0;
q.push(start);
inq[s] = true;
while (q.size()) {
numZF++;
node unode = q.front();
int u = unode.v;
q.pop();
for (int i = 0;i < Adj[u].size();i++) {
node vnode = Adj[u][i];
int v = vnode.v;
if (inq[v] == false && unode.level < maxLevel) {
inq[v] = true;
vnode.level = unode.level + 1;
q.push(vnode);
}
}
}
return numZF;
}
int main() {
scanf("%d%d", &n, &maxLevel);
for (int i = 1;i <= n;i++) {
int tf;
scanf("%d", &tf);
node tempi;
tempi.v = i;
tempi.level = 0;
for (int j = 0;j < tf;j++) {
int idfollow;
scanf("%d", &idfollow);
Adj[idfollow].push_back(tempi);
}
}
scanf("%d", &numQuery);
for (int i = 0;i < numQuery;i++) {
fill(inq, inq + MAX, false);
int query;
scanf("%d", &query);
int fensi = BFS(query);
printf("%d\n", fensi - 1);
}
return 0;
}