思路:广度优先搜索
题目: https://www.luogu.com.cn/problem/P5908
#include <iostream>
#include <vector>
#include<map>
#include <string>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <iomanip>
#include<stack>
#include<queue>
#include<set>
using namespace std;
//众所周知,set能有序地维护同一类型的元素,但相同的元素只能出现一次。
const int N = 2e5 + 5;
queue<int> que;
int h[N], e[N], ne[N], idx=0;
bool st[N];
//int cnt_out[N];
int n,maxx,ans=-1;
int d[N];
void add(int u, int v) {
e[idx] = v;
//w[idx] = val;
ne[idx] = h[u];
h[u] = idx++;
}
void bfs() {
que.push(1);
//d[1] = 0;
while (que.size())
{
int head = que.front();
que.pop();
if (d[head] > maxx) return;
ans += 1;
for (int i = h[head]; i != -1; i = ne[i]) {
int t = e[i];
if (!d[t] && t!=1) {
d[t] = d[head] + 1;
que.push(t);
}
}
}
}
int main() {
memset(h, -1, sizeof h);
cin >> n >> maxx;
for (int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
add(u, v), add(v, u);
}
bfs();
cout << ans << endl;
}