點此查看所有題目集
A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.
?
Input Specification:
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
.The input ends with?N?being 0. That case must NOT be processed.
?
Output Specification:
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.
?這個作為一個30的題,感覺也是很簡單的。題目大意就是給出每個非葉子節點的所有孩子,然后求出該樹的每一層的葉子節點。已知根節點為1。我處理的思路為先存下每個節點的孩子。然后遍歷的時候,尋找出每一層的節點,如果該節點沒有孩子了,就說明為葉子節點。這樣循環遍歷就能求出所有的節點。
#include<bits/stdc++.h>
using namespace std;const int maxn = 106;//建一個樹 求每一層的葉子節點個數 01為根節點map<int,vector<int> >node;map<int,vector<int> >vc;//表示前幾層 每層的節點
int ans[maxn];
int main()
{int N,M;cin >> N >> M;for(int i = 0;i<M;i++){int rt,k;cin >> rt >> k;for(int j = 0;j<k;j++){int x;cin >> x;node[rt].push_back(x);}}vc[1].push_back(1);//表示根節點只有1 也是第一層int lim = 0;for(int i = 2;i<100;i++){for(int j = 0;j<vc[i-1].size();j++)//拿出上一層節點{int nw = vc[i-1][j];for(int k = 0;k<node[nw].size();k++){int ci = node[nw][k];vc[i].push_back(ci);if(node[ci].size()==0)ans[i]++;//當層存在空姐點}}if(vc[i].size()==ans[i]){lim = i;break;}}if(N==0);else if(N==1){cout << 1;}else {cout << 0;for(int i = 2;i<=lim;i++){cout<<" " << ans[i];}}return 0;
}