算法1 BFS
Time Complexity: $O(N * Q)$ 至多10的6次方
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int n, l, k, x;
int bfs(vector<vector<int>>& g, int s) {
queue<int> q{{s}};
vector<int> seen(n + 1);
seen[s] = 1;
int steps = 0, num = 0;
while (not q.empty() && steps <= l) {
size_t sz = q.size();
while (sz--) {
const int cur = q.front(); q.pop();
++num;
for (const auto& nxt : g[cur]) {
if (seen[nxt]) continue;
q.emplace(nxt);
seen[nxt] = 1;
}
}
++steps;
}
return num - 1;
}
// debug helper function
void printGraph(vector<vector<int>>& g) {
for (int u = 1; u <= n; ++u) {
printf("%d: [", u);
for (const auto& v : g[u]) printf(" %d", v);
printf("]\n");
}
putchar('\n');
}
int main(int argc, char** argv) {
cin >> n >> l;
// build the directed graph
vector<vector<int>> g(n + 1);
for (int i = 1; i <= n; ++i) {
cin >> k;
while (k--) {
cin >> x;
g[x].emplace_back(i);
}
}
cin >> k;
while (k--) {
cin >> x;
cout << bfs(g, x) << endl;
}
return 0;
}
TODO 算法2:Floyd