PAT (Advanced Level) Practice A1004 Counting Leaves (30 分)(C++)(甲级)(树、层次遍历)

原题链接:A1004 Counting Leaves

#include
#include
#include
#include 
#include 
using namespace std;

typedef struct PTNode
{
    vector<int> child;
} PTNode;
PTNode PTree[100010];

void BFS(int ID)//广度优先搜索思想,或者说层次遍历思想
{
    queue<int> Q;
    Q.push(ID);
    int last_ID = 1, cnt = 0;//last_ID指向本行最后一个
    while(!Q.empty())
    {
        ID = Q.front();
        Q.pop();
        if(!(PTree[ID].child).size()) cnt++;//本层无孩子的节点数
        for(int i=0; i<(PTree[ID].child).size(); i++)
        {
            Q.push(PTree[ID].child[i]);//孩子入队
        }
        if(ID == last_ID)
        {
            if(ID != 1) printf(" ");//本行结束,打印数据
            printf("%d", cnt);
            last_ID = Q.back();//并更新last_ID和计数器
            cnt = 0;
        }
    }
}

int main()
{
    int N, M, K;
    scanf("%d %d", &N, &M);
    for(int i=0, ID, child_id; i<M; i++)
    {
        scanf("%d %d", &ID, &K);
        for(int j=0; j<K; j++)
        {
            scanf("%d", &child_id);
            (PTree[ID].child).push_back(child_id);
        }
    }
    BFS(1);//层次遍历
    return 0;
}



你可能感兴趣的:(PAT甲级刷题笔记)