#include <bits/stdc++.h>
#define FOR(i, beg, ed, etr) for(ll i = beg;i <= ed;i += etr)
#define FORN(i, beg, ed, etr) for(ll i = beg;i >= ed;i -= etr)
#define all(x) x.begin(), x.end()
#define F first
#define pb push_back
#define con continue
#define S second
using namespace std;
typedef long long ll;
typedef double db;
typedef long double ld;
typedef pair<int,int> pii;
const ll inf = 1e9;
const ll INF = 1e18;
const ll N = 5e3 + 5;
const ll maxn = 5e6;
const ll MOD = 998244353;
int a[N],f[N];
vector <int> g[N];
int dep[N],id[N];
void dfs(int v,int p = 0){
id[dep[v]] = a[v];
for(int to : g[v]){
if(to == p)con;
dep[to] = dep[v] + 1;
dfs(to,v);
}
}
int dp[N],suf[N];
void solve(){
int n;cin >> n;
FOR(i, 1, n, 1){
cin >> a[i];
}
FOR(i, 1, n, 1){
cin >> f[i];
}
FORN(i, n, 1, 1){
suf[i] = max(suf[i+1],f[i]);
}
bool s1 = 1;
FOR(i, 2, n, 1){
int u,v;cin >> u >> v;
g[u].pb(v);
g[v].pb(u);
if(g[v].size() > 2 || g[u].size() > 2)s1 = 0;
}
if(g[1].size() > 1)s1 = 0;
dep[1] = 1;
dfs(1);
FOR(i, 1, n, 1){
dp[i] = dp[i-1] + suf[id[i] + 1];
int mx = id[i];
bool was = 0;
FORN(j, i- 1, 1, 1){
if(id[j] + 1== id[j+1]){
}
else if(id[j+1] == 0){
int d = id[j];
if(mx > id[j] || (was == 1 && id[j] + 1 != mx))break;
mx = id[j] + 1;
was = 1;
}
else break;
if(was == 0)dp[i] = max(dp[i],dp[j-1] + suf[mx+1]);
else dp[i] = max(dp[i],dp[j-1] + f[mx]);
}
}
cout << dp[n];
}
main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
ll abd = 1;
// cin >> abd;
FOR(i, 1, abd, 1){
solve();
}
}
Compilation message (stderr)
code1.cpp:74:1: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
74 | main(){
| ^~~~| # | 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... |