PAT (Advanced Level) 1004 Counting Leaves

题意

给你一棵树,根结点为01,问每层有多少叶子。

思路

水~

代码

#include <bits/stdc++.h>
using namespace std;
int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	int n, m;
	while (cin >> n >> m) {
		vector<vector<int>> son(n);
		for (int i = 0; i < m; ++i) {
			int id, k;
			cin >> id >> k;
			for (int j = 0, x; j < k; ++j) {
				cin >> x;
				son[id - 1].push_back(x - 1);
			}
		}
		vector<int> leaf(105);
		int max_dep = 0;
		function<void(int, int)> dfs = [&](int id, int dep) {
			if (son[id].size() == 0) {
				max_dep = max(max_dep, dep);
				leaf[dep]++;
				return;
			}
			for (auto e : son[id])
				dfs(e, dep + 1);
		};
		dfs(0, 0);
		for (int i = 0; i <= max_dep; ++i) {
			cout << leaf[i] << (i == max_dep ? '\n' : ' ');
		}
	}
	return 0;
} 

HINT

不定时更新更多题解,详见 git ! ! !

发布了97 篇原创文章 · 获赞 16 · 访问量 4015

猜你喜欢

转载自blog.csdn.net/abcdefbrhdb/article/details/104653164