#include #ifdef LOCAL #include #else #define debug(...) void(0) #endif struct FunctionalGraph { int n, L; std::vector visit; std::vector> loops, G; FunctionalGraph(int n) : n(n), L(1), visit(n), G(n), nxt(n, -1) {} void add_edge(int u, int v) { assert(0 <= u and u < n); assert(0 <= v and v < n); nxt[u] = v; } void build() { for (int i = 0; i < n; i++) { if (visit[i] != 0) continue; std::vector loop; dfs(i, loop); if (not loop.empty()) loops.emplace_back(loop); } for (int i = 0; i < n; i++) { if (visit[i] < 0) { G[nxt[i]].emplace_back(i); } } } private: std::vector nxt; void make_loop(int s, std::vector& loop) { loop.emplace_back(s); visit[s] = L; for (int cur = nxt[s]; cur != s; cur = nxt[cur]) { loop.emplace_back(cur); visit[cur] = L; } } int dfs(int v, std::vector& loop) { visit[v] = -L; int u = nxt[v]; if (visit[u] == -L) { make_loop(v, loop); L++; return 0; } else if (visit[u] == 0) { int res = dfs(u, loop); if (res == 0) return 0; return visit[v] = res; } return visit[v] = (visit[u] > 0 ? -visit[u] : visit[u]); } }; using namespace std; typedef long long ll; #define all(x) begin(x), end(x) constexpr int INF = (1 << 30) - 1; constexpr long long IINF = (1LL << 60) - 1; constexpr int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; template istream& operator>>(istream& is, vector& v) { for (auto& x : v) is >> x; return is; } template ostream& operator<<(ostream& os, const vector& v) { auto sep = ""; for (const auto& x : v) os << exchange(sep, " ") << x; return os; } template bool chmin(T& x, U&& y) { return y < x and (x = forward(y), true); } template bool chmax(T& x, U&& y) { return x < y and (x = forward(y), true); } template void mkuni(vector& v) { sort(begin(v), end(v)); v.erase(unique(begin(v), end(v)), end(v)); } template int lwb(const vector& v, const T& x) { return lower_bound(begin(v), end(v), x) - begin(v); } template T ceil(T x, T y) { assert(y >= 1); return (x > 0 ? (x + y - 1) / y : x / y); } template T floor(T x, T y) { assert(y >= 1); return (x > 0 ? x / y : (x - y + 1) / y); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector A(N), B(N), C(N); cin >> A >> B >> C; FunctionalGraph G(N); for (int i = 0; i < N; i++) G.add_edge(i, --C[i]); G.build(); auto g = G.G; auto loops = G.loops; auto dfs = [&](auto self, int v, ll x) -> ll { ll sum = A[v] - 1LL * B[v] * x; for (int& u : g[v]) { ll ch = self(self, u, x); if (ch < 0) sum += ch; } return sum; }; auto check = [&](ll x) -> bool { for (int i = 0; i < N; i++) { if (B[i] > 0 and ceil(IINF, 1LL * B[i]) <= x) { return false; } } for (auto& loop : loops) { ll sum = 0; for (int& r : loop) { ll val = dfs(dfs, r, x); sum += val; } if (sum < 0) return false; } return true; }; ll lb = 0, ub = IINF; while (ub - lb > 1) { ll mid = (lb + ub) >> 1; (check(mid) ? lb : ub) = mid; } cout << lb << '\n'; return 0; }