1004 Counting Leaves (30分)

Posted 000what

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1004 Counting Leaves (30分)相关的知识,希望对你有一定的参考价值。

今天在热心网友的督促下完成了第一道PAT编程题。 太久没有保持训练了,整个人都很懵。 解题方法: 1.读懂题意 2.分析重点 3.确定算法 4.代码实现 该题需要计算每层的叶子节点个数,所以选用BFS 还有一个关键问题是 如何记录一层的开始和结束 另外,对于新手来说,图的存储也是一个知识点 容易忽略特殊取值情况下的答案: 当非叶节点个数为0,只有根节点一个点,所以直接输出1 而其他情况下,第一层叶子节点数为0

/**/
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <stack>
#include <queue>

typedef long long LL;
typedef unsigned long long ULL;
using namespace std;

bool Sqrt(LL n) { return (LL)sqrt(n) * sqrt(n) == n; }
const double PI = acos(-1.0), ESP = 1e-10;
const LL INF = 99999999999999;
const int inf = 999999999, maxN = 100 + 24;
int N, M;
int ans[maxN], d[maxN];
vector< vector<int> >  E(maxN);

int main()
{
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    scanf("%d%d", &N, &M);
    for(int i = 0; i < M; i++) {
        int u, v, k; scanf("%d%d", &u, &k);
        d[u] = k;
        for(int j = 0; j < k; j++) {
            scanf("%d", &v);
            E[u].push_back(v);
        }
    }
    memset(ans, 0, sizeof ans);
    queue<int> Q, W;
    Q.push(1);
    if(!M) { printf("1"); return 0; } 
    printf("0");

    int h = 1;
    while(!Q.empty()) {
        int x = Q.front(), e = d[x], count = 0;
        Q.pop();
        for(auto u : E[x]) {
            if(d[u] > 0) { W.push(u); count++; }
        }
        ans[h] += e - count;

        if(Q.empty()) {
            Q = W;
            while(W.size()) W.pop();
            h++;
        }
    }
    for(int i = 1; i < h; i++) printf(" %d", ans[i]);

    return 0;
}
/*
    input:
    output:
    modeling:
    methods:
    complexity:
    summary:
*/

以上是关于1004 Counting Leaves (30分)的主要内容,如果未能解决你的问题,请参考以下文章

PAT 1004 Counting Leaves (30分)

1004 Counting Leaves (30 分)

PTA 1004 Counting Leaves (30)(30 分)(建树dfs或者bfs,未AC 段错误)

A1004 Counting Leaves (30分)

1004 Counting Leaves (30分)

1004_Counting Leaves (30分)[bfs/dfs]