1004. Counting Leaves
1004. Counting Leaves (30)
Input
Each input file contains one test case. Each case starts with a line containing 0 < N < 100, the number of nodes in a tree, and M (< N), the number of non-leaf nodes. Then M lines follow, each in the format:
ID K ID[1] ID[2] ... ID[K]where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID's of its children. For the sake of simplicity, let us fix the root ID to be 01.
Output
For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.
The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output "0 1" in a line.
Sample Input2 1 01 1 02Sample Output
0 1
1 #include <iostream>
2 #include <fstream>
3 #include <vector>
4 #include <string>
5 #include <algorithm>
6 #include <map>
7 #include <stack>
8 #include <cmath>
9 #include <queue>
10 #include <set>
11
12
13 using namespace std;
14
15
16
17 int main()
18 {
19
20
21 int N , M;
22 map<string,string> parent;
23 multimap<string,string> children;
24 set<string> nodes;
25 set<string> fnodes;
26 set<string> lnodes;
27 nodes.insert("01");
28
29 cin >> N >> M;
30
31 for( int i = 0 ; i < M ; ++i )
32 {
33 string fid;
34
35 cin >> fid;
36
37 int cn;
38
39 cin >> cn;
40
41 for( int i = 0 ; i < cn ; ++i )
42 {
43 string sid;
44 cin >> sid;
45
46 parent.insert(make_pair( sid , fid ));
47 children.insert( make_pair( fid , sid ) );
48 nodes.insert( sid );
49
50 }
51
52 fnodes.insert(fid);
53 }
54
55 for( set<string>::iterator i = nodes.begin() ; i != nodes.end() ; ++i )
56 {
57 set<string>::iterator it;
58
59 it = fnodes.find(*i);
60
61 if( it == fnodes.end() )
62 {
63 lnodes.insert( *i );
64 }
65 }
66
67 int level[100];
68
69 int max_level = 0;
70
71 for( int i = 0 ; i < 100 ; ++i )
72 {
73 level[i] = 0;
74 }
75
76 for( set<string>::iterator i = lnodes.begin() ; i != lnodes.end() ; ++i )
77 {
78 string id = *i;
79
80 int l = 0;
81
82 map<string,string>::iterator it;
83
84 it = parent.find( id );
85
86 while( it != parent.end() )
87 {
88 ++l;
89 id = parent[id];
90
91 if( id == "01" )
92 {
93 break;
94 }
95
96 it = parent.find( id );
97 }
98 if( l > max_level )
99 {
100 max_level = l;
101 }
102
103 ++level[l];
104 }
105
106 for( int i = 0 ; i <= max_level ; ++i )
107 {
108 if( i != 0 )
109 {
110 printf(" ");
111 }
112 cout << level[i];
113 }
114
115 cout << endl;
116
117
118 return 0;
119 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步