7-21 Counting Leaves

題目

題意: 給定樹的結點個數n,m個非葉子結點的孩子,要求輸出樹的每層孩子個數

tip:建樹+層序遍歷

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> no_child(100);
vector<vector<int>> fam(100);
int maxdepth=-1;
void dfs(int index,int depth) {
	if(!fam[index].size()) {
		no_child[depth]++;
		maxdepth=max(maxdepth,depth);
	} else {
		for(int i=0; i<fam[index].size(); ++i)
			dfs(fam[index][i],depth+1);
	}
}
int main() {
	int n,m;
	cin>>n>>m;
	while(n) {
		for(int i=0;i<100;++i)
		fam[i].clear();
		no_child.clear();
		maxdepth=-1;
		if(n==1)
			cout<<1<<endl;
		else {
			for(int i=0; i<m; ++i) {
				int id,k;
				cin>>id>>k;
				for(int j=0; j<k; ++j) {
					int t;
					cin>>t;
					fam[id].push_back(t);
				}
			}
			dfs(1,0);
			cout<<no_child[0];
			for(int i=1; i<=maxdepth; ++i)
				cout<<" "<<no_child[i];
			cout<<endl;
		}
		cin>>n>>m;
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章