Submission #1189396

#TimeUsernameProblemLanguageResultExecution timeMemory
1189396mychecksedadNestabilnost (COI23_nestabilnost)C++20
12 / 100
1608 ms287948 KiB
/* Author : Mychecksdead  */
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define MOD (1000000000+7)
#define MOD1 (998244353)
#define pb push_back
#define all(x) x.begin(), x.end()
#define en cout << '\n'
#define ff first
#define ss second
#define pii pair<int,int>
#define vi vector<int>
const int N = 1e6+100, M = 1e5+10, K = 52, MX = 30;


int n, par[N];
ll a[N], f[N], dp[N], suf[N];
vi g[N];

ll dfs(int v, int p){
  if(dp[v] != -1) return dp[v];
  queue<int> q;
  q.push(v);
  ll before_zero = 0, with_zero = 0;
  ll mx = a[v];
  while(!q.empty()){
    int u = q.front(); q.pop();
    mx = max(mx, a[u]);
    for(int x: g[u]){
      if(x == par[u]) continue;
      if(a[x] == a[u] + 1){
        q.push(x);
      }else{
        before_zero += dfs(x, u);
      }
    }
  }
  before_zero += suf[mx + 1];
  q.push(v);
  ll k = mx + 1;
  while(!q.empty()){
    int u = q.front(); q.pop();
    for(int x: g[u]){
      if(x == par[u]) continue;
      if(a[x] == (a[u] + 1) % k){
        q.push(x);
      }else{
        // cout << v << ' ' << x << ' ' << u << '\n';
        with_zero += dfs(x, u);
      }
    }
  }
  with_zero += f[k];
  // cout << v << ' ' << with_zero << ' ' << before_zero << ' ' << k << '\n';
  return dp[v] = min(with_zero, before_zero);
}

void pre(int v, int p){
  par[v] = p;
  for(int u: g[v]) if(u != p) pre(u, v);
}

void solve(){
  cin >> n;
  for(int i = 1; i <= n; ++i){
    cin >> a[i];
  }
  for(int i = 1; i <= n; ++i){
    cin >> f[i];
    dp[i] = -1;
  }
  suf[n] = f[n];
  for(int i = n-1; i >= 1; --i) suf[i] = min(suf[i + 1], f[i]);
  for(int i = 1; i < n; ++i){
    int u, v; cin >> u >> v;
    g[u].pb(v);
    g[v].pb(u);
  }
  pre(1, 1);
  cout << dfs(1, 1);
}


int main(){
  cin.tie(0); ios::sync_with_stdio(0);
  int tt = 1, aa;
  // freopen("in.txt", "r", stdin);
  // freopen("out.txt", "w", stdout);
  while(tt--){
    solve();
    en;
  }
  cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" seconds\n";
  return 0;
} 
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...