32962023-02-24 14:11:11zsomborSzállításcpp17Accepted 40/4013ms6204 KiB
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int n, k, ans = 0;
vector <int> p(2e4 + 1, 0);
vector <int> d(2e4 + 1, 0);
vector <int> mxd(2e4 + 1, 0);
vector <vector <int>> g(2e4 + 1);
vector <pair <int, int>> l;

void atrendez(int x) {
    mxd[x] = d[x];
    int mxi = 0;
    for (int i : g[x]) {
        d[i] = d[x] + 1;
        atrendez(i);
        mxd[x] = max(mxd[x], mxd[i]);
        if (mxd[i] > mxd[mxi]) { p[mxi] = 1; mxi = i; }
        else p[i] = 1;
    }
}

void level(int x) {
    if (!g[x].size()) l.push_back({ -d[x],x });
    for (int i : g[x]) {
        d[i] = d[x] + 1;
        level(i);
    }
}

int main()
{
    cin >> n >> k;
    for (int i = 1; i <= n; i++) {
        cin >> p[i];
        g[p[i]].push_back(i);
    }
    atrendez(1);
    for (int i = 1; i <= n; i++) g[i].resize(0);
    for (int i = 1; i <= n; i++) g[p[i]].push_back(i);
    level(1);
    for (int i = 1; i <= n; i++) if (g[i].size() && l.size() < k) l.push_back({ 0,i });
    sort(l.begin(), l.end());
    for (int i = 0; i < k; i++) ans -= l[i].first;
    cout << ans << endl;
    for (int i = 0; i < k; i++) cout << l[i].second << " ";
}
SubtaskSumTestVerdictTimeMemory
base40/40
1Accepted0/03ms2904 KiB
2Accepted0/06ms3792 KiB
3Accepted2/23ms3508 KiB
4Accepted2/23ms3796 KiB
5Accepted2/24ms4012 KiB
6Accepted2/23ms3872 KiB
7Accepted2/23ms3792 KiB
8Accepted2/24ms4048 KiB
9Accepted2/24ms4132 KiB
10Accepted2/23ms4136 KiB
11Accepted2/24ms4260 KiB
12Accepted2/24ms4520 KiB
13Accepted2/26ms5048 KiB
14Accepted2/26ms5148 KiB
15Accepted2/26ms5164 KiB
16Accepted2/27ms5228 KiB
17Accepted3/37ms5680 KiB
18Accepted3/38ms5760 KiB
19Accepted3/313ms6204 KiB
20Accepted3/313ms6184 KiB