编程语言
首页 > 编程语言> > 2021团体程序设计天梯赛 L2-2 病毒溯源

2021团体程序设计天梯赛 L2-2 病毒溯源

作者:互联网

思路:

水题,略过

Tip:

#include <bits/stdc++.h>

using namespace std;

const int maxn = 10000 + 5;
int father[maxn];
bool isp[maxn];
int ceng[maxn];
int maxceng = 0;
vector<int> vmaxn;

int dfs(int now) {
    if (ceng[now])
        return ceng[now];
    if (father[now] == now) {
        ceng[now] = 1;
        return 1;
    }
    ceng[now] = dfs(father[now]) + 1;
    return ceng[now];
}

int main() {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++)
        father[i] = i;
    for (int i = 0; i < n; i++) {
        int t;
        cin >> t;
        if (t == 0)
            isp[i] = true;
        for (int j = 1; j <= t; j++) {
            int x;
            cin >> x;
            father[x] = i;
        }
    }
    for (int i = 0; i < n; i++) {
        if (isp[i]) {
            ceng[i] = dfs(i);
            if (ceng[i] > maxceng) {
                maxceng = ceng[i];
                vmaxn.clear();
                int now = i;
                while (father[now] != now) {
                    vmaxn.push_back(now);
                    now = father[now];
                }
                vmaxn.push_back(now);
            } else if (ceng[i] == maxceng) {
                vector<int> vnow;
                int now = i;
                while (father[now] != now) {
                    vnow.push_back(now);
                    now = father[now];
                }
                vnow.push_back(now);
                bool flag = false;
                for (int k = maxceng - 1; k >= 0; k--) {
                    if (vnow[k] < vmaxn[k]) {
                        flag = true;
                        break;
                    } else if (vnow[k] > vmaxn[k]) {
                        flag = false;
                        break;
                    }
                }
                if (flag)
                    vmaxn = vnow;
            }
        }
    }
    cout << maxceng << endl;
    bool first = true;
    for (int k = maxceng - 1; k >= 0; k--) {
        if (first) {
            first = false;
            cout << vmaxn[k];
        } else
            cout << " " << vmaxn[k];
    }
    return 0;
}

  

标签:int,father,vnow,L2,2021,天梯,now,ceng,vmaxn
来源: https://www.cnblogs.com/Whiteying/p/14707800.html