Submission

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

Score: 100

User: fluke

Problemset: D.Drunk

Language: cpp

Time: 0.151 second

Submitted On: 2025-02-17 13:56:06

#include <bits/stdc++.h>
#define ll long long
#define f first 
#define s second 
#define pii pair<int,int>
#define DB system("pause");
using namespace std;

ll drink(int node , vector <int> &next ,vector <ll> &drunk, vector <ll> &mem){
    if(next[node] == node)return drunk[node];
    else if(mem[node] != -1)return mem[node];
    
    return mem[node] = drink(next[node],next,drunk,mem) + drunk[node];
}


int main(){
ios::sync_with_stdio(false);cin.tie(0);
    int n;
    cin>>n;
    vector <int> next(n+1);
    vector <ll> drunk(n+1);
    vector <ll> mem(n+1,-1);

    for(int i=1;i<=n;i++)cin>>drunk[i];
    for(int i=1;i<=n;i++)cin>>next[i];

    ll max_ans = 0 ;
    for(int i=1;i<=n;i++){
        max_ans = max(max_ans , drink(i,next,drunk,mem));
    }

    cout<<max_ans;
}