美文网首页PAT (Advanced Level) Practice
1004 Counting Leaves (30point(s)

1004 Counting Leaves (30point(s)

作者: iphelf | 来源:发表于2020-02-28 00:16 被阅读0次

    树,DFS。

    关键符号说明:

    Symbol Explanation
    rt Root node of the tree being DFSed on
    d Depth
    #include<cstdio>
    #include<vector>
    #include<cstring>
    using namespace std;
    
    const int MAXN=100;
    vector<int> child[MAXN];
    int ans[MAXN];
    int depth;
    
    void dfs(int rt,int d){
        depth=max(depth,d+1);
        if(child[rt].empty()){
            ans[d]++;
            return;
        }
        for(int i=0;i<child[rt].size();i++)
            dfs(child[rt][i],d+1);
    }
    
    int main(void) {
    //    freopen("in.txt","r",stdin);
        int n,m,k,r,c;
        scanf("%d%d",&n,&m);
        while(m--){
            scanf("%d%d",&r,&k);
            for(int i=0;i<k;i++){
                scanf("%d",&c);
                child[r].push_back(c);
            }
        }
        memset(ans,0,sizeof ans);
        depth=0;
        dfs(1,0);
        for(int i=0;i<depth;i++) printf("%d%c",ans[i],i==depth-1?'\n':' ');
        return 0;
    }
    
    /*
    Sample Input:
    2 1
    01 1 02
    
    Sample Output:
    0 1
    */
    

    相关文章

      网友评论

        本文标题:1004 Counting Leaves (30point(s)

        本文链接:https://www.haomeiwen.com/subject/bkeqhhtx.html