1004. Counting Leaves (30)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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 1 01 1 02
Sample Output
0 1
算每层的叶子数 你们都用DFS 我偏用BFS 呵呵哒
#define DeBUG #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <string> #include <set> #include <sstream> #include <map> #include <list> #include <bitset> using namespace std ; #define zero {0} #define INF 0x3f3f3f3f #define EPS 1e-6 #define TRUE true #define FALSE false typedef long long LL; const double PI = acos(-1.0); //#pragma comment(linker, "/STACK:102400000,102400000") inline int sgn(double x) {return fabs(x) < EPS ? 0 : (x < 0 ? -1 : 1);} #define N 100005 struct Node { int lev; int a; Node(int x, int l) { a = x; lev = l; } }; int main() { #ifdef DeBUGs freopen("/Users/sky/Documents/sublime project/in.txt", "r", stdin); #endif int n, m; int level[200]; while (scanf("%d%d", &n, &m) + 1) { memset(level, 0, sizeof(level)); std::vector<int> v[101]; int a, b, c; for (int i = 0; i < m; i++) { scanf("%d %d", &a, &b); for (int j = 0; j < b; j++) { scanf("%d", &c); v[a].push_back(c); } } if (n == 1) { printf("1\n"); continue; } Node *n = new Node(1, 1); queue<Node>Q; Q.push(*n); int maxx = 0; while (!Q.empty()) { Node now = Q.front(); Q.pop(); int nowlevel = now.lev; maxx = max(maxx, nowlevel); for (int i = 0; i < v[now.a].size(); i++) { Node *it = new Node(v[now.a][i], nowlevel + 1); if (v[it->a].size() == 0) level[it->lev]++; Q.push(*it); } } printf("%d", level[1]); for (int i = 2; i <= maxx; i++) { printf(" %d", level[i]); } printf("\n"); } return 0; }