152072025-02-16 18:42:06antiTevefarmcpp17Runtime error 0/501ms512 KiB
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <fstream>

using namespace std;

vector<vector<int>> children;
vector<long long> L[2];
vector<int> selected;

void dfs( int u, const vector<long long>& T ){
    L[0][u] = 0;
    L[1][u] = T[u];
    for(int v : children[u]){
        dfs( v, T);
        L[0][u] += max( L[0][v], L[1][v] );
    }
}

void backtrack( int u, bool take_parent){
    if(take_parent){
        selected.push_back(u+1);
        for(int v : children[u]){
            backtrack( v, false );
        }
    }else{
        for(int v : children[u]){
            if(L[1][v] > L[0][v]){
                backtrack( v, true );
            }else{
                backtrack( v, false);
            }
        }
    }
}

int main(){
    ifstream fin("be2.txt");
    int n;
    fin >> n;

    vector<long long> T(n);
    for(int i=0; i<n; i++){
        fin >> T[i];
    }

    children.resize(n);
    int h[n];
    for(int i=1; i<n; i++){
        int parent;
        fin >> parent;
        h[i] = parent;
        h[i]--;
        children[parent - 1].push_back(i);
    }
    L[0].assign(n, 0);
    L[1].assign(n, 0);

    dfs( 0, T );
    long long max_sum = max(L[0][0], L[1][0]);
    cout << max_sum << endl;

    if(L[0][0] < L[1][0]){
        backtrack( 0, true );
    }else{
        backtrack( 0, false );
    }

    cout << selected.size() << endl;
    for(int i=0; i<selected.size(); i++){
        cout << selected[i] << " ";
    }
}
SubtaskSumTestVerdictTimeMemory
base0/50
1Runtime error0/01ms316 KiB
2Runtime error0/01ms512 KiB
3Runtime error0/41ms316 KiB
4Runtime error0/41ms316 KiB
5Runtime error0/41ms508 KiB
6Runtime error0/41ms348 KiB
7Runtime error0/41ms316 KiB
8Runtime error0/61ms316 KiB
9Runtime error0/61ms316 KiB
10Runtime error0/61ms316 KiB
11Runtime error0/61ms360 KiB
12Runtime error0/61ms316 KiB