1004. Counting Leaves (30)
来源:互联网 发布:mac 删除windows分区 编辑:程序博客网 时间:2024/05/22 13:41
题目详情:https://www.patest.cn/contests/pat-a-practise/1004
提交情况:
#include <iostream>#include <vector>#include <string.h>using namespace std;#define N 110vector<int> child[N];int n,m,Levels[N],maxLevel;bool hasChild[N];int queue[N],rear,front,visit[N];void BFS( int start ) //广度优先算法,主要在于记录各个节点是否为叶子节点和节点层次 { rear = front = -1; queue[++rear] = start; visit[start] = 1; Levels[start] = 1; while( front != rear ) { int key = queue[++front]; if( child[key].size() == 0 ) //编号为key的节点没有孩子节点 { hasChild[key] = false; //记录下该节点为叶子节点 } for( int i=0;i<child[key].size();++i ) { queue[++rear] = child[key][i]; Levels[ child[key][i] ] = Levels[key] + 1;//记录下各节点的层次 if( Levels[key]+1 > maxLevel ) maxLevel = Levels[key]+1; } }}int main (){ //处理输入 cin>>n>>m; for( int i=1;i<=m;++i ) { int num,kid,father; cin>>father>>num; for( int j=0;j<num;++j ) { cin>>kid; child[father].push_back(kid); } } //BFS之前的初始化 memset(hasChild,true,sizeof(hasChild)); //一开始对maxLevel赋值为-1,0,提交结果都出现了部分结果正确,改为maxLevel之后才全部正确的 //大概此题隐含着必有一个节点吧 maxLevel = 1; BFS(1);// for( int i=1;i<=n;++i ) //查看hasChild[]数组 // {// if( i == n )// cout<<hasChild[i]<<endl;// else// cout<<hasChild[i]<<" ";// }// for( int i=1;i<=n;++i ) //查看Levels[]数组 // {// if( i == n )// cout<<Levels[i]<<endl;// else// cout<<Levels[i]<<" ";// }// cout<<"maxLevel is "<<maxLevel<<endl; for( int i=1;i<=maxLevel;++i ) //对各个层次的进行遍历,从层次1开始 { int count = 0; for( int j=1;j<=n;++j ) //对每一个节点进行遍历 { if( i == Levels[j] && hasChild[j] == false ) //如果某个节点在第i层上,且为叶子节点 ++count; } //控制输出 if( i == maxLevel ) cout<<count<<endl; else cout<<count<<" "; } return 0;}
另外此题我还出现了一个错误,如下:
int hasChild[N];memset( hasChild,1,sizeof(hasChild) );
在查看hasChild[]数组的时候发现hasChild[]中的数都变为了:16843009。上网查了下,发现原因如下:memset()是按照字节进行赋值的,int类型占4个字节,所以在对int类型变量赋值的时候,每个字节都赋值为1,结果就变为了00000001 00000001 00000001 00000001(二进制,对应的十进制为16843009)。bool类型占一个字节,换成bool类型就达到了预期的效果。
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)
- 【干货】58集团监控业务实践:将网站运行信息透明化
- Eclipse安装svn插件的几种方式
- 区块链和数字货币开发历史上发生哪些被黑事件
- java enum(枚举)使用详解
- Hdu 5187 zhx's contest【思维+快速幂+快速乘】
- 1004. Counting Leaves (30)
- handler 随笔
- 【行人识别】Deep Transfer Learning for Person Re-identification
- JAVA-7-形参及返回值、权限及内容修饰符、内部类(重点是匿名内部类)
- mysql添加图片
- android 横竖屏切换属性和播放视频全屏切换
- volatile
- Android实现类似C#ComBox功能用AutoCompleteTextView实现
- 安卓中OpenGL ES的初步应用