【PAT】A1004. Counting Leaves(DFS)
@(PAT)
链接:https://www.patest.cn/contests/pat-a-practise/1004
思路:
1. 使用DFS,每步先判断该点有没有儿子,如果没有儿子的话,就为叶子节点,计数;如果有儿子的话,遍历所有叶子节点,递归DFS访问所有叶子节点。
2. 树的储存使用:
map<int, vector<int> > alist;
其实就是邻接表的形式,能够很好储存一棵非二叉树。
3. 输入的时候,因为要根据层数输出,所以用num_leave_now记录当前统计到的非叶子节点,每一次输出后增加每一层的叶子节点,当num_leave_now>= num_leave_total的时候就退出循环,这时候所有层数都被访问输出到。
my AC code:
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
using namespace std;
map<int, vector<int> > alist;
int mcount[99]= {0};
bool mDFS(int id, int level) {
if (alist[id].empty()) {
mcount[level]++;
return false;
}
for (int i= 0; i< alist[id].size(); i++) {
mDFS(alist[id][i], level+ 1);
}
return true;
}
int main() {
// n= the num of nodes, m= the num of non-leave nodes
int n, m;
scanf("%d%d", &n, &m);
// Store the tree
for (int i= 0; i< m; i++) {
int id, k;
scanf("%d%d", &id, &k);
for (int j= 0; j< k; j++) {
int sid;
scanf("%d", &sid);
alist[id].push_back(sid);
}
}
// begin DFS
mDFS(1, 0);
int num_leave_now= mcount[0];
int num_leave_total= n- m;
printf("%d", mcount[0]);
for (int i= 1; num_leave_now< num_leave_total; i++) {
printf(" %d", mcount[i]);
num_leave_now+= mcount[i];
}
return 0;
}
DFS使用了递归实现,待复习复习完DFS和BFS后,尝试下使用非递归实现,理论上来说应该是可行的。