PAT甲级 1004 Counting Leaves (30 分)
作者:互联网
题目
分析
想着试试 最近用的BFS算法 加上队列 然后就ac了 代码有待优化 但看了下结果感觉还挺快的
code
#include <stdio.h>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct Node
{
int sun;
int lnum;
vector<int> leafs;
} nodes[110];
int main()
{
int all, left;
cin >> all >> left;
for (int i = 0; i < left; i++)
{
int curr, num;
cin >> curr >> num;
Node node;
node.lnum = num;
vector<int> leaff;
for (int j = 0; j < num; j++)
{
int tmp;
cin >> tmp;
nodes[tmp].sun = 1;
leaff.push_back(tmp);
}
node.leafs = leaff;
nodes[curr] = node;
}
queue<int> q;
q.push(1);
int currlevel = 1;
int currnum = 1;
int res[110] = {0};
while (!q.empty())
{
int a = q.front();
q.pop();
Node fnode = nodes[a];
currnum--;
if(fnode.lnum==0){
res[currlevel]++;
}
for (int i = 0; i < fnode.lnum; i++)
{
q.push(fnode.leafs[i]);
}
if(currnum == 0){
currnum = q.size();
currlevel++;
}
}
for (int i = 1; i < currlevel; i++)
{
if(i!=1) cout<<" ";
cout<<res[i];
}
}
结果
标签:PAT,int,Leaves,currlevel,++,num,currnum,nodes,1004 来源: https://blog.csdn.net/wenzhouxiaomayi77/article/details/113761743