This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
// Author : FatihCihan
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define all(v) v.begin() , v.end()
#define sz(a) (int)a.size()
const int N = 5e3 + 7;
const int inf = 1e18 + 7;
int n , arr[N] , fk[N] , dp[N][N] , mini[N];
vector < int > tree[N];
void f(int node , int par){
for(auto itr : tree[node]){
if(itr == par)continue;
f(itr , node);
}
int tmp[n+1] = {0};
for(int i = 1;i<=n;i++){
for(auto itr : tree[node]){
if(itr == par)continue;
int local_ans = mini[itr];// new component
if((arr[node] + 1) % i == arr[itr] and dp[itr][i] != inf){// continuing same component
local_ans = min(local_ans , dp[itr][i]);
// cout << node << " -> " << itr << " with an " << i << endl;
}
tmp[i] += local_ans;
}
}
mini[node] = inf;
for(int i = 1;i<=n;i++){
if(arr[node] < i){
mini[node] = min(mini[node] , tmp[i] + fk[i]);
dp[node][i] = tmp[i];
}
else{
dp[node][i] = inf;
}
// cout << node+1 << " " << i << " : " << tmp[i] << " ( + " << fk[i] << ")" << endl;
}
// cout << "mini " << node+1 << " : " << mini[node] << endl;
}
void solve(){
cin >> n;
for(int i = 0;i<n;i++)cin >> arr[i];
for(int i = 1;i<=n;i++)cin >> fk[i];
for(int i = 1;i<n;i++){
int a,b;
cin >> a >> b;
a-- , b--;
tree[a].push_back(b);
tree[b].push_back(a);
}
f(0,0);
cout << mini[0] << endl;
}
signed main(){
ios_base::sync_with_stdio(0);cin.tie(0);
int testcase = 1;//cin >> testcase;
while(testcase--)solve();
cerr << 1000.0 * clock() / CLOCKS_PER_SEC << " ms" << 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... |