zoukankan      html  css  js  c++  java
  • 2021团体程序设计天梯赛 L2-2 病毒溯源

    思路:

    dfs+优化

    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;
    }
    

      

  • 相关阅读:
    【福利】乳摇动画初探
    碎裂效果尝试(clip-path篇)
    碎裂效果尝试(canvas篇)
    自己的HTML5 播放器
    纯CSS实现选项卡
    企鹅阿里实习生面试
    关于使用indexedDB的本地存储(3)
    关于使用indexedDB的本地存储(2)
    关于使用indexedDB的本地存储(1)
    关于ajax分段上传文件实例~
  • 原文地址:https://www.cnblogs.com/Whiteying/p/14707800.html
Copyright © 2011-2022 走看看