PAT甲级解题笔记1004-dfs/树的遍历
2018-07-31 13:26
323 查看
PAT甲级解题笔记1004
题意:输入总结点数N(0<N<100),非叶节点数M<N,接下来M行:
非叶节点编号ID(00,01……的形式),其子节点数K,子节点编号ID[0] ID[1] ... ID[K]
输出:每一层叶节点的个数,以空格隔开,结尾无空格。
实现方法:
1.用递归实现dfs
2.使用一维定长(题中说明0<N<100)一维变长(子节点数不定)的vector数组
vector<int> num[100];
num[index].size()
num[id].push_back(nowid);
[code]#include<iostream> #include<algorithm> #include<vector> using namespace std; vector<int> num[100]; int n, m, id, k, nowid; int leave[100] = { 0 }, maxdepth=-1; void dfs(int index, int depth) { if (num[index].size() == 0)//若没有子节点 { leave[depth]++;//对应层数的叶节点数增加1 maxdepth = max(maxdepth, depth);//更新最大层数 return; } for (int i = 0; i < num[index].size(); i++) { dfs(num[index][i], depth+1);//dfs常用递归,判断子节点是否有子节点,层数增加1 } } int main(void) { cin >> n >> m; while (m--) { cin >> id >> k; while (k--) { cin >> nowid; num[id].push_back(nowid); } } dfs(1, 0);//根节点为01,层数为0 cout << leave[0]; for(int i=1;i<=maxdepth;i++) cout << " " << leave[i]; system("PAUSE"); return 0; }
相关文章推荐
- PAT甲级解题笔记1079-dfs/树的遍历
- 1004. Counting Leaves (30)-PAT甲级真题(bfs,dfs,树的遍历,层序遍历)
- 1106. Lowest Price in Supply Chain (25)-PAT甲级真题(dfs,bfs,树的遍历)
- 1079. Total Sales of Supply Chain (25)-PAT甲级真题(dfs,bfs,树的遍历)
- 1115. Counting Nodes in a BST (30)-PAT甲级真题(二叉树的遍历,dfs)
- PAT甲级真题1013. Battle Over Cities (25)(图的遍历,统计强连通分量的个数,dfs)
- 1094. The Largest Generation (25)-PAT甲级真题(bfs,dfs,树的遍历)
- PAT - 甲级 - 1094. The Largest Generation (25)(树的遍历DFS)
- 1021. Deepest Root (25)-PAT甲级真题(图的遍历,dfs,连通分量的个数)
- 1034. Head of a Gang (30)-PAT甲级真题(图的遍历dfs)
- PAT - 甲级 - 1090. Highest Price in Supply Chain (25)(树的遍历DFS)
- 1013. Battle Over Cities (25)-PAT甲级真题(图的遍历,统计强连通分量的个数,dfs)
- PAT - 甲级 - 1004. Counting Leaves (30)(DFS/BFS,二叉树的遍历)
- 1030. Travel Plan (30)-PAT甲级真题(Dijkstra + DFS,输出路径,边权)
- pat 甲级1013 DFS求强连通分量
- 019-dfs.bfs-图的遍历-《算法设计技巧与分析》M.H.A学习笔记
- PAT甲级1001. A+B Format (20)解题报告
- *浙大PAT甲级 1099层次遍历二叉查找树
- PAT(甲级)1004
- 解题笔记(33)——按层次遍历二元树