1004. Counting Leaves (30)

来源:互联网 发布:我的世界mac版材质包 编辑:程序博客网 时间:2024/04/28 11:30
题目:
A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.

Input

Each input file contains one test case. Each case starts with a line containing 0 < N < 100, the number of nodes in a tree, and M (< N), the number of non-leaf nodes. Then M lines follow, each in the format:

ID K ID[1] ID[2] ... ID[K]
where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID's of its children. For the sake of simplicity, let us fix the root ID to be 01.

Output

For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.

The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output "0 1" in a line.

Sample Input
2 101 1 02
Sample Output
0 1
注意:
1、由于自己对图论的算法实现还不是特别熟悉,所以我这里直接用不断遍历查询的方式来计算,而且还是第一次用STL,果然是路漫漫其修远啊!
2、我的解题思路是计算每一层的节点个数,然后判断每个借点节点是否是无子节点,判断的方式是将该节点在输入的M 行非叶nodes中查找有没有对应于该id的行,没有则说明是无子节点,若有则将该id对应的行中的K个节点加入到下一层要计算的节点vector中,以此不断查询。
3、该算法还可以提高效率,对2中每一次查找到非叶nodes时顺便将其删除,可以减小后面判断是否是无子节点时查找的次数。


代码:
#include<iostream>#include<vector>using namespace std;struct node{int ID;int K;vector< int> child;};int main(){// 0 < N < 100, the number of nodes in a tree// M (< N), the number of non-leaf nodesint N,M;cin>>N>>M;vector<node>nodes;nodes.clear();node tempnode;for(int i=0;i<M;++i){tempnode.child.clear();cin>>tempnode.ID>>tempnode.K;int t;for(int j=0;j<tempnode.K;++j){cin>>t;tempnode.child.push_back(t);}nodes.push_back(tempnode);}vector< int>level;level.clear();level.push_back(1);//count the number of non-leaf nodes for every levelwhile(!level.empty()){int num=level.size();vector< int>temp(level);level.clear();//judge if they are non-leaf nodes for all nodes in this levelfor(int i=0;i<temp.size();++i){//seach if this node has childfor(int j=0;j<nodes.size();++j){if(nodes.at(j).ID==temp.at(i)){--num;for(int k=0;k<nodes.at(j).K;++k)level.push_back(nodes.at(j).child.at(k));}}}if(level.empty())cout<<num;else cout<<num<<' ' ;}return 0;}


0 0