首页 > 学院 > 开发设计 > 正文

PAT (Advanced Level) Practise 1004. Counting Leaves (30)

2019-11-06 09:16:42
字体:
来源:转载
供稿:网友

1004. Counting Leaves (30) 时间限制: 400 ms内存限制: 65536 kB代码长度限制: 16000 B判题程序:Standard
  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. Examples

Input
2 101 1 02
Output
0 1

  Notes    作者   CHEN, Yue

  树的节点不超过100个,用数组简单建树即可。注意题目已定义ID为”01”的节点为根节点。

#include <iostream>#include <algorithm>#include <map>#include <vector>#include <functional>#include <string>#include <cstring>#include <queue>#include <set>#include <stack>#include <cmath>#include <cstdio>#include <sstream>#include <iomanip>using namespace std;#define IOS ios_base::sync_with_stdio(false)#define TIE std::cin.tie(0)#define MIN2(a,b) (a<b?a:b)#define MIN3(a,b) (a<b?(a<c?a:c):(b<c?b:c))#define MAX2(a,b) (a>b?a:b)#define MAX3(a,b,c) (a>b?(a>c?a:c):(b>c?b:c))typedef long long LL;typedef unsigned long long ULL;const int INF = 0x3f3f3f3f;const double PI = 4.0*atan(1.0);const double eps = 1e-6;const int maxn = 105;struct Node{ vector<int> ve;}nodes[maxn];int n, m, x, f, ch, num;int hn[maxn], maxh;string id1, id2;map<string, int> ma;void dfs(int nn,int h){ if (h > maxh) maxh = h; Node & node = nodes[nn]; if (node.ve.empty()) hn[h]++; h++; for (int i = 0; i < node.ve.size(); i++){ dfs(node.ve[i], h); }}int main(){ IOS; cin >> n >> m; maxh = 0; ma["01"] = 0; num = 1; for (int i = 0; i < m; i++){ cin >> id1; if (ma.count(id1)){ f = ma[id1]; }else{ ma[id1] = num; f = num; num++; } cin >> x; for (int j = 0; j < x; j++){ cin >> id2; if (ma.count(id2)){ ch = ma[id2]; } else{ ma[id2] = num; ch = num; num++; } nodes[f].ve.push_back(ch); } } dfs(0, 0); for (int i = 0; i <= maxh-1; i++) printf("%d ", hn[i]); printf("%d/n", hn[maxh]); //system("pause");}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表