您的位置:首页 > 其它

1004. Counting Leaves (30)

2017-04-17 10:39 330 查看
题目详情:https://www.patest.cn/contests/pat-a-practise/1004

提交情况:


#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
#define N 110
vector<int> child
;
int n,m,Levels
,maxLevel;
bool hasChild
;
int queue
,rear,front,visit
;
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[fat
4000
her].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
;
memset( hasChild,1,sizeof(hasChild) );


在查看hasChild[]数组的时候发现hasChild[]中的数都变为了:16843009。上网查了下,发现原因如下:memset()是按照字节进行赋值的,int类型占4个字节,所以在对int类型变量赋值的时候,每个字节都赋值为1,结果就变为了00000001 00000001 00000001 00000001(二进制,对应的十进制为16843009)。bool类型占一个字节,换成bool类型就达到了预期的效果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: