统计树的每一层上叶子节点的个数
Sample Input
2 1
01 1 02
Sample Output
0 1
#include <iostream> #include <iomanip> #include <string> #include <map> #include <vector> using namespace std; void fun(vector<string> &v, map<string,vector<string>> &MapTree) { vector<string> next; int leaf = 0; vector<string>::iterator iter = v.begin(); while(iter != v.end()) { map<string,vector<string>>::iterator iterMap = MapTree.find(*iter); if (iterMap != MapTree.end()) { vector<string> vec = iterMap->second; if (vec.size() == 0) { leaf++; } else { next.insert(next.end(),vec.begin(),vec.end()); } } else { leaf++; } iter++; } cout<<" "<<leaf; if (next.size() == 0) { return; } fun(next,MapTree); } int main() { map<string,vector<string>> MapTree; int N,M; cin>>N>>M; while(M--) { string str; int K; vector<string> VNode; cin>>str>>K; while(K--) { string strNode; cin>>strNode; VNode.push_back(strNode); } MapTree[str] = VNode; } map<string,vector<string>>::iterator iter = MapTree.find("01"); if (iter != MapTree.end()) { vector<string> v = iter->second; if (v.size() > 0) { cout<<"0"; fun(v, MapTree); } else { cout<<"1"; } } else { cout<<"1"; } return 0; }