1004. Counting Leaves (30) 解析和记录

1.定义一个类：主要有vector<int> child 和 colour组成；child 用来存储该节点的子代，colour 用来标记叶子（WHITE）和中间节点(BLACK)。

2.由于 0 < N < 100, 为了简化计算定义类数组来进行寻址，注意数组大小可以定义成101，方便直接从1开始寻址

3.输入数据，用类数组的数据结构来表示这颗树，并对节点进行着色，将子代放入vector

4.通过BFS广度优先思想来遍历这颗树，用队列queue来实现广度优先算法，其算法复杂度为O(N)

#include <iostream>
#include <vector>
#include <sstream>
#include <queue>
#include <cstring>

#define WHITE 0
#define BLACK 1
#define MAX_NODE 500
using namespace std;

struct node{
vector<int> child;
int colour;
node(): colour(WHITE) {}
};

queue<int> list;
int n_n;
int m_n;
node array[MAX_NODE];

int main(void)
{
string line;
while(getline(cin, line))
{
/*input*/
int record;
stringstream sss(line);
sss >> n_n;
if(n_n == 1)
{
cout << 1 << "\n";
continue;
}
sss >> m_n;
memset(array, 0, sizeof(node) * MAX_NODE);
for(int i = 0; i < m_n; i++)
{
int id;
int k;
getline(cin, line);
stringstream ss(line);
ss >> id;
ss >> k;
for(int j = 0; j < k; j++)
{
int temp;
ss >> temp;
array[id].child.push_back(temp);
array[id].colour = BLACK;
}

}

/*process*/
record = 1;
list.push(1);
cout << 0;
while(!list.empty())
{
int times = 0;
int next_record = 0;
for(int j = 0; j < record; j++)
{
int temp;
temp = list.front();
list.pop();
for(unsigned int i = 0; i < array[temp].child.size(); i++)
{
if(array[array[temp].child[i]].colour ==  BLACK)
{
list.push(array[temp].child[i]);
next_record++;
}
else
times++;
}
}
record  = next_record;
cout << " " << times;
}
cout << "\n";
}

return 0;
}