首页 > 其他 > 详细

1004 Counting Leaves (30分)(DFS)

时间:2020-02-08 16:36:07      阅读:54      评论:0      收藏:0      [点我收藏+]
//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;
}

 

1004 Counting Leaves (30分)(DFS)

原文:https://www.cnblogs.com/QRain/p/12283435.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!