注意点:
1. 简单的树遍历,使用DFS(深度遍历)来计算树的深度
2. 非叶子节点的孩子使用vector进行存储
代码如下:
#include <iostream>
#include <string.h>
#include <stack>
#include <math.h>
#include <vector>
#include <algorithm>
#define MAXNUM 0x3f3f3f3f
#define MAXLEN 101
#define STARTTIME 8 * 60 * 60
#define ENDTIME 21 * 60 * 60
#define max(a, b) (((a) > (b)) ? (a) : (b))
using namespace std;
vector<int> parents[MAXLEN];
int levels[MAXLEN];
int maxLevel = -1;
void countLevel(int parent, int level)
{
int i;
if(level > maxLevel)
maxLevel = level;
if(parents[parent].size() == 0)
levels[level] ++;
else
{
for(i = 0; i < parents[parent].size(); ++ i)
countLevel(parents[parent][i], level + 1);
}
}
int main()
{
int N, M;
int i, j;
int parent, child, childNum;
scanf("%d %d", &N, &M);
for(i = 0; i < M; ++ i)
{
scanf("%d %d", &parent, &childNum);
for(j = 0; j < childNum; ++ j)
{
scanf("%d", &child);
parents[parent].push_back(child);
}
}
memset(levels, 0, sizeof(levels));
countLevel(1, 0);
for(i = 0; i <= maxLevel; ++ i)
{
if(i == 0)
printf("%d", levels[i]);
else
printf(" %d", levels[i]);
}
return 0;
}