Cpp
#include <iostream>
using namespace std;
int n, m;
int id, k;
int parent[101];
int level[101];
int get_level(int p)
{
int level = 0;
do
{
level++;
p = parent[p];
} while (p != parent[p]);
return level;
}
bool haschild(int p)
{
for (int i = 1; i <= n; i++)
{
if (parent[i] == p)
{
return true;
}
}
return false;
}
int main(int argc, char const *argv[])
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++)
{
scanf("%d%d", &id, &k);
for (int j = 1; j <= k; j++)
{
int c;
scanf("%d", &c);
parent[c] = id;
}
}
int dept = 1;
for (int i = 1; i <= n; i++)
{
int i_level = get_level(i);
level[i] = i_level;
if (dept < i_level)
{
dept = i_level;
}
}
for (int i = 1; i <= dept; i++)
{
int leaf_num = 0;
// 遍历
for (int j = 1; j <= n; j++)
{
if (level[j] == i && haschild(j) == false)
{
leaf_num++;
}
}
if (i < dept)
{
printf("%d ", leaf_num);
}
else if (i == dept)
{
printf("%d", leaf_num);
}
}
return 0;
}
Java
import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.Scanner;
/**
* Main
*/
public class Main {
static int n, m;
static int id, k;
static int[] parent = new int[101];
static int[] level = new int[101];
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
n = sc.nextInt();
m = sc.nextInt();
// 读m个非叶节点的信息, 建立树结构
for (int i = 1; i <= m; i++) {
id = sc.nextInt();
k = sc.nextInt();
for (int j = 1; j <= k; j++) {
int c = sc.nextInt();
parent[c] = id;
}
}
sc.close();
// 得到树的深度
int dept = 1;
for (int i = 1; i <= n; i++) {
int iLevel = getLevel(i);
level[i] = iLevel;
if (dept < iLevel) {
dept = iLevel;
}
}
// 遍历每一层
for (int i = 1; i <= dept; i++) {
int leafNum = 0;
for (int j = 1; j <= n; j++) {
if (level[j] == i && haschild(j) == false) {
leafNum++;
}
}
if (i < dept) {
System.out.printf("%d ", leafNum);
} else if (i == dept) {
System.out.printf("%d", leafNum);
}
}
// reader.close();
}
// 得到一个节点的深度
public static int getLevel(int p) {
int level = 0;
do {
level++;
p = parent[p];
} while (p != parent[p]);
return level;
}
// 判断一个节点是否有子树
public static boolean haschild(int p) {
for (int i = 1; i <= n; i++) {
if (parent[i] == p) {
return true;
}
}
return false;
}
}