bfs:记录层序
1 #include<iostream> 2 #include<vector> 3 #include<queue> 4 #include<map> 5 #include<set> 6 #include<cmath> 7 #include<cstdio> 8 #include<cstdlib> 9 #include<cstring> 10 #include<algorithm> 11 using namespace std; 12 13 const int maxSize = 500 + 10; 14 int N, M, K, Root, vRoot, maxLevel; 15 vector<int> nodes[maxSize]; 16 int level[maxSize], book[maxSize]; 17 18 void bfs() { 19 level[1] = 0; //默认1号为根节点,其处在第0层 20 maxLevel = 0; //输出范围(树的层数) 21 queue<int> que; 22 que.push(1); 23 while (!que.empty()) { 24 int v = que.front(); 25 que.pop(); 26 if (nodes[v].size() == 0) book[level[v]]++; //该节点无子节点 27 for (int i = 0; i < nodes[v].size(); i++) { //该节点有子节点 28 que.push(nodes[v][i]); 29 level[nodes[v][i]] = level[v] + 1; //标志子节点的层数 30 } 31 maxLevel = max(maxLevel, level[v]); 32 } 33 } 34 35 int main() 36 { 37 while (cin >> N >> M) { 38 memset(nodes, 0, sizeof(nodes)); 39 memset(level, 0, sizeof(level)); 40 memset(book, 0, sizeof(book)); 41 for (int i = 0; i < M; i++) { 42 cin >> Root >> K; 43 for (int j = 0; j < K; j++) { 44 cin >> vRoot; 45 nodes[Root].push_back(vRoot); 46 } 47 } 48 bfs(); 49 cout << book[0]; 50 for (int i = 1; i <= maxLevel; i++) { 51 cout << " " << book[i]; 52 } 53 cout << endl; 54 } 55 return 0; 56 }
dfs:
1 #include<iostream> 2 #include<vector> 3 #include<queue> 4 #include<map> 5 #include<set> 6 #include<cmath> 7 #include<cstdio> 8 #include<cstdlib> 9 #include<cstring> 10 #include<algorithm> 11 using namespace std; 12 13 const int maxSize = 500 + 10; 14 int N, M, K, Root, vRoot, maxLevel; 15 vector<int> nodes[maxSize]; 16 int book[maxSize]; 17 18 void dfs(int root,int level) { 19 if (nodes[root].size() == 0) { 20 book[level]++; 21 maxLevel = max(maxLevel, level); 22 return; 23 } 24 for (int i = 0; i < nodes[root].size(); i++) { 25 dfs(nodes[root][i], level + 1); 26 } 27 } 28 29 int main() 30 { 31 while (cin >> N >> M) { 32 memset(nodes, 0, sizeof(nodes)); 33 memset(book, 0, sizeof(book)); 34 for (int i = 0; i < M; i++) { //关联表建树 35 cin >> Root >> K; 36 for (int j = 0; j < K; j++) { 37 cin >> vRoot; 38 nodes[Root].push_back(vRoot); 39 } 40 } 41 maxLevel = 0; 42 dfs(1,0); //根节点1,为第0层 43 cout << book[0]; 44 for (int i = 1; i <= maxLevel; i++) { 45 cout << " " << book[i]; 46 } 47 cout << endl; 48 } 49 return 0; 50 }