Submission

Status:

[PPPPPPPPPP][PPPxS][PPPPxSSS][PPPxSSSSSS]

Subtask/Task Score:

{10/10}{0/5}{0/15}{0/70}

Score: 10

User: singtoppy

Problemset: D.Drunk

Language: cpp

Time: 0.111 second

Submitted On: 2026-03-20 21:27:39

#include<bits/stdc++.h>

using namespace std;

#define ll long long
#define pb push_back
#define pii pair<int, int>
#define pll pair<ll, ll>
#define ttt pair<string, array<int, 2>>

const int dir[4][2] = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}};
const int MOD = 1e9 + 7;
const ll INF64 = (ll) 1e18;

int n, d[1000005], x[1000005], dist[100005];
bool vis[1000005];
vector<pii> g[100005];

void solve() {
	cin >> n;
	priority_queue<array<int, 2>> pq;
	for(int i = 1; i <= n; i++) 
		cin >> d[i];
	for(int i = 1; i <= n; i++){
		cin >> x[i];
		if(x[i] == i)
			pq.push({d[i], i});
		else
			g[x[i]].push_back({i, d[i]});
	}
	int res = 0;
	while(!pq.empty()) {
		auto [s, i] = pq.top();
		pq.pop();
		res = max(res, s);
		if(vis[i])
			continue;
		vis[i] = true;
		for(auto [j, ns] : g[i]) {
			if(!vis[j] && s + ns > dist[j]) {
				dist[j] = s + ns;
				pq.push({s + ns, j});
			}
		}
	}
	cout << res;
}


int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	solve();
	return 0;
}