题意:无向连通图中,每条边距离为 1,问其中距离起点距离大于 d 的点数。
分析:由起点出发,标记每个点距离起点的距离。
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e5 + 10, INF = 0x3f3f3f3f;
int n, m, dis[N];
vector<int> G[N];
void bfs() {
memset(dis, 0x3f, sizeof(dis));
queue<int> q;
q.push(0), dis[0] = 0;
while (q.size()) {
auto u = q.front(); q.pop();
if (dis[u] > m) continue;
for (auto v : G[u]) {
if (dis[v] > dis[u] + 1) {
dis[v] = dis[u] + 1;
q.push(v);
}
}
}
}
int main() {
int t; scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &m);
for (int i = 0; i <= n; i++) G[i].clear();
for (int i = 1, x, y; i < n; i++) {
scanf("%d%d", &x, &y);
G[x].push_back(y);
G[y].push_back(x);
}
bfs();
int ans = 0;
for (int i = 1; i < n; i++)
ans += (dis[i] > m);
printf("%d\n", ans);
}
return 0;
}