1004 Counting Leaves (30分)(DFS)

//dfs模版
#include <vector>
#include <iostream>
using namespace std;

struct node
{
    vector<int>children;
}t[101];
int ithLevel[101];//保存第i层叶子结点的数目
int maxLevel=-1;//保存最大层数

void dfs(int root,int depth)
{
    if(t[root].children.size()==0)
    {
        if(depth>maxLevel)
            maxLevel=depth;
        ithLevel[depth]++;
        return;
    }
    for(int i=0;i<t[root].children.size();i++)
        dfs(t[root].children[i],depth+1);
}

 int main()
{
    int n,m;
    cin>>n>>m;
    fill(ithLevel,ithLevel+100,0);
    for(int i=0;i<m;i++)
    {
        int id,size;
        cin>>id>>size;
        for(int j=0;j<size;j++)
        {
            int child;
            cin>>child;
            t[id].children.push_back(child);
        }
    }
    dfs(1,0);
    for(int i=0;i<maxLevel;i++)
        cout<<ithLevel[i]<<" ";
    cout<<ithLevel[maxLevel];
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/QRain/p/12283435.html