该题具有很大的练习价值。
DFS-解题如下:
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
const int maxn = 1010;
int N, L;
vector<int> G[maxn];
int layer[maxn]; // 记录当前结点的层号
bool vis[maxn] = {false}; // 记录当前结点是否已访问
void DFS(int u, int deepth) {
vis[u] = true;
layer[u] = deepth;
if(deepth == L) return ;
for(auto i:G[u])
if(!vis[i] || layer[i] > deepth + 1) // 解题核心,
DFS(i, deepth + 1);
}
int main() {
scanf("%d %d", &N, &L);
int childNum, temp;
for(int i = 1; i <= N; i++) {
scanf("%d", &childNum);
for(int j = 0; j < childNum; j++) {
scanf("%d", &temp);
G[temp].push_back(i);
}
}
int queryNum, query, num;
scanf("%d", &queryNum);
while(queryNum --) {
num = 0;
memset(vis, false, sizeof(vis));
memset(layer, 0, sizeof(layer));
scanf("%d", &query);
DFS(query, 0);
for(int i = 1; i <= N; i++)
num += layer[i] > 0 ? 1 : 0;
printf("%d\n", num);
}
return 0;
}
BFS-解题如下
#include<iostream>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 1010;
struct Node{
int id, layer;
Node (int _id, int _layer): id(_id), layer(_layer){}
Node () {}
};
int N, L, numForward;
vector<Node> G[maxn];
bool inq[maxn];
void BFS(int u) {
queue<Node> q;
Node start = Node(u, 0);
q.push(start);
inq[start.id] = true;
while(!q.empty()) {
Node top = q.front();
q.pop();
int curId = top.id;
for(int i = 0; i < G[curId].size(); i++) {
Node next = G[curId][i];
next.layer = top.layer + 1;
if(inq[next.id] == false && next.layer <= L) {
q.push(next);
inq[next.id] = true;
numForward++;
}
}
}
}
int main() {
Node user;
scanf("%d %d", &N, &L);
int childNum, temp;
for(int i = 1; i <= N; i++) {
user.id = i;
scanf("%d", &childNum);
for(int j = 0; j < childNum; j++) {
scanf("%d", &temp);
G[temp].push_back(user);
}
}
int queryNum, query, num;
scanf("%d", &queryNum);
while(queryNum --) {
numForward = 0;
memset(inq, false, sizeof(inq));
scanf("%d", &query);
BFS(query);
printf("%d\n", numForward);
}
return 0;
}