这道题能看懂英文题意,就好办,联想到BFS
题目大意:给n个用户,最大层数L,然后依次给出n个用户关注(粉Follow)的用户编号, Follow是粉的意思,Followers是粉丝数量.这里有vector Follow来表示图结点
然后以待查寻编号为起始编号BFS进行L层的遍历count结点总数
代码如下
#include <cstdio>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <cstring>
#include <vector>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <ctype.h>
using namespace std;
const int maxn = 1010;
struct node {
int id, layer;
};
vector<node> Follower[maxn];
int visit[maxn] = { 0 };
int BFS(int s, int L) {
int numFollow = 0;
node start;
start.id = s;
start.layer = 0;
queue<node> q;
q.push(start);
visit[s] = 1;
while (!q.empty()) {
node top = q.front();
q.pop();
int u = top.id;
for (int i = 0; i < Follower[u].size(); i++) {
node next = Follower[u][i];
next.layer = top.layer + 1;
if (visit[next.id] == 0 && next.layer <= L) {
q.push(next);
visit[next.id] = 1;
numFollow++;
}
}
}
return numFollow;
}
int main() {
int n, L;
scanf("%d%d", &n, &L);
for (int i = 1; i <= n; i++) {
node user;
user.id = i;
int k, tFollow;
scanf("%d", &k);
for (int j = 0; j < k; j++) {
scanf("%d", &tFollow);
Follower[tFollow].push_back(user);
}
}
int querry, s;
scanf("%d", &querry);
for (int i = 0; i < querry; i++) {
scanf("%d", &s);
memset(visit, 0, sizeof(visit));
int numFollow = BFS(s, L);
printf("%d\n", numFollow);
}
return 0;
}