PAT 1004. Counting Leaves
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
int main()
{
int n,m,par_id,k,child_id,par[101],i,j;
vector<int> v;
queue<int> Q,Q_tmp;
cin>>n>>m;
for(i=1; i<=n; i++)
par[i] = i;
for(i=0; i<m; i++)
{
cin>>par_id;
cin>>k;
for(j=0; j<k; j++)
{
cin>>child_id;
par[child_id] = par_id; //child_id的父亲是par_id
}
}
bool isFirst = true;
int t = 0;
Q.push(1);
while( !Q.empty() )
{
int iCount = 0;
while( !Q.empty() )//遍历当前层次的节点,对没有孩子的节点进行计数。
{
bool hasChild = false;
int curId = Q.front();
Q.pop();
for(i=1; i<=n; i++)
if(par[i] == curId && curId != i)
{
hasChild = true;
Q_tmp.push(i);
}
if(!hasChild)
iCount++;
}
if(isFirst)
{
cout<<iCount;
isFirst = false;
}
else
cout<<" "<<iCount;
//将Q_tmp中的内容复制到Q中,进入下一层次的计数
while( !Q_tmp.empty() )
{
int t = Q_tmp.front();
Q_tmp.pop();
Q.push(t);
}
}
cout<<endl;
return 0;
}
多学习,多总结。

浙公网安备 33010602011771号