1004. Counting Leaves (30)
来源:互联网 发布:多空风险指标源码 编辑:程序博客网 时间:2024/04/28 03:25
考察树的层次遍历,使用数组保存每个节点的孩子节点,在判断时不太方便。使用vector更方便对孩子节点的操作。笔者使用的是队列的方式来层次遍历,另一种可参考的方式是递归的深度遍历。
笔者代码:
#include<cstdio>#include<cstring>#include<queue>using namespace std;#define N 101int main(){ int n,m,k,i,id,j; int child[N][N]; memset(child,-1,sizeof(child)); scanf("%d %d",&n,&m); for(i =0;i<m;i++){ scanf("%d %d",&id,&k); for(j=0;j<k;j++){ scanf("%d",&child[id][j]); } } int nochild[N]; memset(nochild,0,sizeof(nochild)); int level=1; id =1; queue<int> que ; que.push(id); int len = 1; while(!que.empty()){ id = que.front(); que.pop(); len--; i=0; if(child[id][i]==-1){ nochild[level]++; } else while(child[id][i]!=-1){ que.push(child[id][i]); i++; } if(len==0){ level++; len = que.size(); } } bool flag = true; for(i=1;i<level;i++){ if(flag){ flag = false; } else{ printf(" "); } printf("%d",nochild[i]); }}
递归深度遍历的方法:
#include <cstdio> #include <cstdlib> #include <cstring> #include <map> #include <vector> using namespace std; map<int,vector<int> >adjlist; int record[101]={0}; void DFS(int id,int level){ if(adjlist[id].empty()){ ++record[level]; return; } vector<int>::iterator ite = adjlist[id].begin(); for(;ite!=adjlist[id].end();++ite){ DFS(*ite,level+1); } } int main(){ //freopen("in.txt","r",stdin); int n,m,id,k,sid,i,cle,cnt; scanf("%d %d",&n,&m); cle = n-m; while(m--){ scanf("%d %d",&id,&k); while(k--){ scanf("%d",&sid); adjlist[id].push_back(sid); } } DFS(1,0); printf("%d",record[0]); cnt = record[0]; for(i=1;cnt<cle;++i){ printf(" %d",record[i]); cnt += record[i]; } printf("\n"); return 0; }
0 0
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- hello niuniu
- DataTable转化为泛型集合
- openSSL AES 加密引擎代码分析
- 学习笔记:git学习1
- notes on codes of SPECT
- 1004. Counting Leaves (30)
- Android拍照选择图片上传服务器自定义控件
- Failed to save the updated manifest to the file ".\Debug\Test.exe.embed
- 论"老黄牛"的价值
- Android加载大分辨率图片到手机内存中的实例方法
- 字符串和多维数组
- poj解题报告——1061
- Java程序员笔试面试之String3
- 作业 :判断三角形是否成立