#include <bits/stdc++.h>
using namespace std;
#define int long long
#define arr array
#define vec vector
const int N = 5e3 + 5, INF = 1e18;
int n;
arr<int, N> vl, cst;
arr<vec<int>, N> adj;
arr<arr<int, N>, N> dp;
arr<int, N> mn;
void dfs(int u = 1, int pr = -1) {
for (int v : adj[u])
if (v != pr) dfs(v, u);
mn[u] = INF;
for (int c = 1; c <= n; c++) {
for (int v : adj[u]) {
if (v == pr) continue;
int tk = ((vl[u] + 1) % c == vl[v]) ? dp[v][c] : INF;
int lv = mn[v];
dp[u][c] += min(tk, lv);
}
if (c < vl[u] + 1) dp[u][c] = INF;
// cout << u << " " << c << ": " << dp[u][c] << endl;
mn[u] = min(mn[u], dp[u][c] + cst[c]);
}
}
signed main() {
// freopen("a.in", "r", stdin);
cin >> n;
for (int u = 1; u <= n; u++) cin >> vl[u];
for (int c = 1; c <= n; c++) cin >> cst[c];
for (int i = 1; i < n; i++) {
int u, v; cin >> u >> v;
adj[u].push_back(v), adj[v].push_back(u);
}
assert(n == 1 || (adj[1].size() == 1 && adj[n].size() == 1));
dfs();
int ans = INF;
for (int c = 1; c <= n; c++) ans = min(ans, dp[1][c] + cst[c]);
cout << ans << endl;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |