• L2-026 小字辈 (25 point(s)) (BFS)


    补题链接:Here

    本题给定一个庞大家族的家谱,要请你给出最小一辈的名单。

    输入格式:

    输入在第一行给出家族人口总数 N(不超过 100 000 的正整数) —— 简单起见,我们把家族成员从 1 到 N 编号。随后第二行给出 N 个编号,其中第 i 个编号对应第 i 位成员的父/母。家谱中辈分最高的老祖宗对应的父/母编号为 -1。一行中的数字间以空格分隔。

    输出格式:

    首先输出最小的辈分(老祖宗的辈分为 1,以下逐级递增)。然后在第二行按递增顺序输出辈分最小的成员的编号。编号间以一个空格分隔,行首尾不得有多余空格。

    输入样例:

    9
    2 6 5 5 -1 5 6 4 7
    

    输出样例:

    4
    1 9
    

    这道题只需要简单的 BFS 搜索一下就可以了

    AC 代码

    #include <bits/stdc++.h>
    using namespace std;
    #define Max 100005
    vector<int> vec[Max];  //// 用来存图的
    set<int> m;            // 保存结点的
    int fa = 1;            // 记录最大字辈的下标
    int bfs() {
        queue<int> q;
        int daishu = 0;  //  记录代数,题目第一个数据让我们输出有多少代人
        q.push(fa);  //  之前记录的最大辈分,把它压到队列,进行bfs
        q.push(-1);  //  这个 -1 ,相当是一个标记变量, 说明这一层结束了,
        int flog = 0;  // 看它有没有孩子的标记变量
        while (!q.empty()) {
            int t = q.front();
    
            if (t == -1) {      /// -1 ,说明遍历完这一代人了,
                daishu++;       //  代数++
                if (flog == 1)  //  有孩子, flog == 1 ,清空set
                    m.clear();
                flog = 0;  //
                q.pop();
                q.push(
                    -1);  // 这一代人的孩子都压到队列了,说明下一代人都遍历完了,压
                          // -1 到队列中
                t = q.front();
            }
    
            q.pop();
            if (t == -1)
                continue;
            // cout<<t<<" ";
            for (int i = 0; i < vec[t].size(); i++) {
                q.push(vec[t][i]);  //  把 t 的孩子都压到队列中
                flog = 1;           // 这一代人,有孩子, flog == 1
            }
            m.insert(t);  //
        }
        return daishu;
        // cout<<" daishu  = "<<daishu<<endl;
    }
    int main() {
        int a;
        cin >> a;
        for (int i = 1; i <= a; i++) {
            int temp;
            cin >> temp;
            if (temp == -1) {
                if (a == 1) {
                    cout << "1" << endl;
                    cout << i << endl;
                    return 0;
                }
                fa = i;  //  当前字辈是最大字辈,记录下来
                continue;
            }
            vec[temp].push_back(
                i);  //  当前 i 是 temp的一个孩子,那么就是temp有一个孩子,指向i
        }
        cout << bfs() << endl;
        set<int>::iterator it;
        for (it = m.begin(); it != m.end(); it++) {
            if (it == m.begin())
                cout << *it;
            else
                cout << " " << *it;
        }
        // cout<<"A"<<endl;
    
        return 0;
    }
    

    The desire of his soul is the prophecy of his fate
    你灵魂的欲望,是你命运的先知。

  • 相关阅读:
    104_如何彻底删除VMware
    学习笔记(25)- NLP的几个概念
    学习笔记(24)- plato-训练中文模型
    学习笔记(23)- plato-准备中文语料
    学习笔记(22)- plato-训练端到端的模型
    学习笔记(21)- texar 文本生成
    学习笔记(35)-安装pyhanlp
    NLP直播-1 词向量与ELMo模型
    线上学习-语言模型 language model
    学习笔记(20)- Google LaserTagger
  • 原文地址:https://www.cnblogs.com/RioTian/p/14686785.html
Copyright © 2020-2023  润新知