1004 Counting Leaves - dfs、树的处理

思路:前向星+dfs

代码如下:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
#include<cmath>
#include<set>
#include<sstream>
#define ll long long
using namespace std;
const int N=105,INF=0x3f3f3f3f;
int flag[N],A[N],head[N],cnt=0,shen=0;
struct proc{int to,next;};
proc edge[N];

void addEdge(int from,int to){
    edge[cnt].to=to;
    edge[cnt].next=head[from];
    head[from]=cnt++;
}

void dfs(int now,int dep){
    shen=max(shen,dep);
    int res;
    if(flag[now])res=0;
    else res=1;
    A[dep]+=res;
    for(int i=head[now];i!=-1;i=edge[i].next){
        int dot=edge[i].to;
        dfs(dot,dep+1);
    }
}

int main(){
    int n,m,u,k,a,b;
    scanf("%d%d",&n,&m);
    memset(head,-1,sizeof(head));
    memset(flag,0,sizeof(flag));
    while(m--){
        scanf("%1d%1d",&a,&b);
        u=a*10+b;
        scanf("%d",&k);
        if(k)flag[u]=k;
        while(k--){
            scanf("%1d%1d",&a,&b);
            int tmp=a*10+b;
            addEdge(u,tmp);
        }
    }
    dfs(1,1);
    printf("%d",A[1]);
    for(int i=2;i<=shen;i++)printf(" %d",A[i]);
    printf("\n");
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值