Submission

Status:
[PPPPPPPPPP][PPPPP][PPPPPPPP][PPPPPPPPxS]

Score: 30

User: Nathlol2

Problemset: D.Drunk

Language: cpp

Time: 0.588 second

Submitted On: 2025-01-05 17:07:02

#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define pb push_back
using namespace std;

int n;
const int maxN = 1000005;
vector<int> a(maxN);
vector<int> nex(maxN);
vector<int> root;
vector<vector<int>> g(maxN);
vector<bool> vis(maxN, false);
ll ans = 0;

ll dfs(int node) {
    vis[node] = true;
    ll mx = a[node];
    
    for (auto i : g[node]) {
        if (!vis[i]) {
            mx = max(mx, a[node] + dfs(i));
        }
    }
    return mx;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    vector<int> in(n, 0);
    for (int i = 0; i < n; i++) {
        cin >> nex[i];
        nex[i]--;
        if (nex[i] != i) {
            g[nex[i]].pb(i);
        }else{
            root.pb(i);
        }
    }
    for (auto i : root) {
        ans = max(ans, dfs(i));
    }
    cout << ans;
}