【1004 30 bfs】 Counting Leaves
传送门
题意
给出 \(n\) 个节点的树,\(m\) 个子根的子节点数据,每组包含根结点 \(id\),然后 \(k\) 个孩子节点,求出树从根向外每一层都有多少个叶节点,规定 \(01\) 号节点是整颗树的根节点
数据范围
\(1\leq n\leq 100\)
\(1\leq m\leq n\)
题解
bfs过程中一次遍历一整层,每次先计算当前层的深度,通过判断当前的节点是否有孩子来判断当前节点是否为叶节点,叶子节点就累加当前层数量
Code
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
vector<vector<int>> g(N);
int n, m, depth;
vector<int> lvs(N);
void bfs() {
queue<int> q; q.push(1);
while (!q.empty()) {
int sz = q.size();
++depth;
for (int i = 0; i < sz; i++) {
int t = q.front(); q.pop();
if (g[t].size() == 0) {
lvs[depth]++;
continue;
}
for (auto it : g[t]) {
q.push(it);
}
}
}
}
int main() {
cin >> n >> m;
while (m--) {
int root, k; cin >> root >> k;
for (int i = 0; i < k; i ++) {
int child; cin >> child;
g[root].push_back(child);
}
}
bfs();
for (int i = 1; i <= depth; i++) {
if (i != 1) cout << " ";
cout << lvs[i];
}
return 0;
}

浙公网安备 33010602011771号