-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpat_advance_1004.cpp
103 lines (96 loc) · 1.99 KB
/
pat_advance_1004.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <stdio.h>
#include <iostream>
#include <vector>
#define M 101
using namespace std;
int cnt[M] = {0};
int maxlevel = -1;
vector<vector<int>> v(M);
//DFS algorithm
void dfs(int index, int level){
if (v[index].size() == 0){
cnt[level]++;
maxlevel = maxlevel > level ? maxlevel : level;//remenber the maxlevel when every iterator
return;
}
else{
for (int i = 0; i < v[index].size(); i++)
{
dfs(v[index][i],level+1);
}
}
}
int main(){
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++)
{
int index, k, temp;
cin >> index >> k;
for (int j = 0; j < k; j++)
{
cin >> temp;
v[index].push_back(temp);
}
}
dfs(1,0);
cout << cnt[0];
for (int i = 1; i <= maxlevel; i++)
{
cout << ' ' << cnt[i];
}
return 0;
}
//This is the second method of 1004, this way is litter harder to understand than DFS
#include <stdio.h>
#include <iostream>
#include <queue>
#include <vector>
#define M 101
using namespace std;
queue<int> q;
vector<vector<int>> v(M);
int level[M] = { 0 }, cnt[M] = { 0 };//level refer to the level of every node;cnt refer to nums of every level
int maxlevel = -1;//the largest level of the tree
int main(){
//initialize the tree whose node contains its every child
int n, m;
cin >> n >> m;
int index, k, temp;
for (int i = 0; i < m; i++)
{
cin >> index >> k;
for (int j = 0; j < k; j++)
{
cin >> temp;
v[index].push_back(temp);
}
}
/*BFS start*/
//initialize the queue
q.push(1);
level[1] = 0;
while (!q.empty()){
index = q.front();//when reuse the parameter 'index',notice the value of 'index'
q.pop();
maxlevel = maxlevel > level[index] ? maxlevel : level[index];//choose the larger level
//When the node is leaf make arr cnt plus 1
if (v[index].size() == 0){
cnt[level[index]]++;
}
else{
for (int j = 0; j < v[index].size(); j++)
{
level[v[index][j]] = level[index] + 1;
q.push(v[index][j]);
}
}
}
/*BFS end*/
cout << cnt[0];
for (int i = 1; i <= maxlevel; i++)
{
cout << ' ' << cnt[i];
}
return 0;
}