Problem:
F: ボタンの木
問題文
$N$ 頂点 $N-1$ 辺からなる木があり、$i$ 番目の辺は $u_i$ 番目の頂点と $v_i$ 番目の頂点を接続しています。
各頂点にはボタンが咲いており、$i$ 番目の頂点に咲いているボタンをボタン $i$ と呼ぶことにします。
はじめ、ボタン $i$ の美しさは $a_i$ です。
ボタン $i$ を押すたびに、ボタン $i$ の美しさを隣接するボタンに $1$ ずつ分け与えます。
すなわち、$i$ 番目の頂点に $c_1, ..., c_k$ 番目の頂点が隣接している場合、ボタン $i$ の美しさが $k$ 減少し、ボタン $c_1, ..., c_k$ の美しさがそれぞれ $1$ ずつ増加します。
このとき、負の美しさのボタンを押しても良いし、ボタンを押した結果あるボタンの美しさが負になっても良いです。
あなたの目的はボタン $1, 2, ..., N$ の美しさをそれぞれ $b_1, ..., b_N$ にすることです。
最小で合計何回ボタンを押せば目的を達成できるでしょうか。
制約
入力はすべて整数である
$1 \leq N \leq 10^5$
$1 \leq u_i, v_i \leq N$
$-1000 \leq a_i, b_i \leq 1000$
$\sum_i a_i = \sum_i b_i$
与えられるグラフは木である
与えられる入力において目的は必ず達成できる
入力
入力は以下の形式で標準入力から与えられる。
$N$
$u_1$ $v_1$
$\vdots$
$u_{N-1}$ $v_{N-1}$
$a_1$ $a_2$ $...$ $a_N$
$b_1$ $b_2$ $...$ $b_N$
出力
目的を達成するためにボタンを押す合計回数の最小値を出力せよ。
入力例1
4
1 2
1 3
3 4
0 3 2 0
-3 4 5 -1
出力例1
4
次のように合計 $4$ 回ボタンを押すことで目的を達成でき、このときが最小です。
ボタン $1$ を $2$ 回押します。ボタン $1, 2, 3, 4$ の美しさがそれぞれ $-4, 5, 4, 0$ に変化します。
ボタン $2$ を $1$ 回押します。美しさがそれぞれ $-3, 4, 4, 0$ に変化します。
ボタン $4$ を $1$ 回押します。美しさがそれぞれ $-3, 4, 5, -1$ に変化します。
入力例2
5
1 2
1 3
3 4
3 5
-9 5 7 1 8
-7 4 5 1 9
出力例2
3

Submitted solutions:

code_snippet: // AOJ #3142 Tree of Peony
// 2025.4.23

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

#define gc() getchar_unlocked()

int Cin() {
	int n = 0; int c = gc();
	if (c == '-') {	c = gc();
		do n = 10*n + (c & 0xf), c = gc(); while (c >= '0');
		return -n;
	}
	do n = 10*n + (c & 0xf), c = gc(); while (c >= '0');
	return n;
}

int main(){
    int N = Cin();

    vector<vector<int>> adj(N+1);
    for(int i = 0; i < N-1; i++){
        int u = Cin(), v = Cin();
        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    vector<ll> a(N+1), b(N+1), d(N+1), D(N+1), P(N+1);
    for(int i = 1; i <= N; i++) a[i] = Cin();
    for(int i = 1; i <= N; i++){
        b[i] = Cin();
        d[i] = b[i] - a[i];
        D[i] = d[i];
    }

    vector<int> parent(N+1), order;
    order.reserve(N);
    stack<int> st;
    st.push(1);
    parent[1] = 0;
    while(!st.empty()){
        int u = st.top(); st.pop();
        order.push_back(u);
        for(int v: adj[u]){
            if(v == parent[u]) continue;
            parent[v] = u;
            st.push(v);
        }
    }

    for(int i = N-1; i >= 0; --i){
        int u = order[i];
        if(u != 1) D[parent[u]] += D[u];
    }

    ll C = LLONG_MIN;
    for(int u: order){
        if(u == 1) P[u] = 0;
        else P[u] = P[parent[u]] + D[u];
        C = max(C, P[u]);
    }

    ll ans = 0;
    for(int i = 1; i <= N; i++) ans += (C - P[i]);
    cout << ans << endl;
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 13844
final_rank: 1

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll=int64_t;

int n;
ll ans=0;
vector<vector<int>> g(100000);
vector<ll> a(100000),c(100000),d(100000,0);

void dfs(int t,int p){ 
  c[t]=1;
  for(int i:g[t]){
    if(i==p) continue;
    dfs(i,t);
    c[t]+=c[i];
    d[t]=max(d[t],-a[i]);
  }
  ans+=d[t];
  for(int i:g[t]){
    if(i==p) continue;
    ans+=(c[i]*(d[t]+a[i]));
    a[t]+=a[i];
    a[i]=0;
  }
  if(p>=0){
    a[t]-=d[t];
    a[p]+=d[t];
    if(a[t]>0){
      ans+=c[t]*a[t];
      a[p]+=a[t];
      a[t]=0;
    }
  }
  return;
}


int main() {

  int n;
  cin >> n;
  int u,v;
  for(int i=0;i<n-1;i++){
    cin >> u >> v;
    u--;v--;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  for(int i=0;i<n;i++) cin >> a[i];
  ll b;
  for(int i=0;i<n;i++){
    cin >> b;
    a[i]-=b;
  }

  dfs(0,-1);
  cout << ans << endl;
}
accuracy: 1
time_ms: 70
memory_kb: 18076
final_rank: 5

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll=int64_t;

int n;
ll ans=0;
vector<vector<int>> g(100000);
vector<ll> a(100000);

tuple<ll,ll,int> dfs(int t,int p){ //pairは、親への＋/自身/子、孫の合計数
  if(g[t].size()==1){ 
    if(a[t]>0){
      ll at=a[t];
      a[t]=0;
      ans+=at;
      return make_tuple(at,0,1);
    }
    return make_tuple(0,a[t],1);
  }
  vector<pair<ll,int>> ch;
  ll chmin=0;
  int mini=-1,nums=0;
  for(int i=0;i<(int)g[t].size();i++){
    if(g[t][i]==p) continue;
    auto [at,ca,num]=dfs(g[t][i],t);
    
    if(at>0) a[t]+=at;
    if(chmin>ca){
      chmin=ca;
      mini=i;
    }
    ch.emplace_back(ca,num);
    nums+=num;
  }
  int chn=(int)ch.size();
  ll at=0;
  if(mini!=-1){
    ans+=(-chmin);
    if(t!=0){
      at+=(-chmin);
      a[t]+=chmin*(chn+1);
    }else{
      a[t]+=chmin*chn;
    }
    for(int i=0;i<chn;i++){
      if(i==mini) continue;
      auto [ca,num]=ch[i];
      ans+=((ca-chmin)*num);
      a[t]+=(ca-chmin);
    }
  }
  
  if(a[t]>0){
    at+=a[t];
    ans+=a[t];
    ans+=(a[t]*nums);
    a[t]=0;
  }
  return make_tuple(at,a[t],nums+1);
}


int main() {

  int n;
  cin >> n;
  int u,v;
  for(int i=0;i<n-1;i++){
    cin >> u >> v;
    u--;v--;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  for(int i=0;i<n;i++) cin >> a[i];
  ll b;
  for(int i=0;i<n;i++){
    cin >> b;
    a[i]-=b;
  }

  auto [at,ca,num]=dfs(0,-1);
  cout << ans << endl;
  //cout << at << " " << ca << " " << num << endl;
}
accuracy: 0.08695652173913043
time_ms: 30
memory_kb: 7884
final_rank: 16

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll=int64_t;

int n,ans=0;
vector<vector<int>> g(100000);
vector<int> a(100000);

tuple<int,int,int> dfs(int t,int p){ //pairは、親への＋/自身/子、孫の合計数
  if(g[t].size()==1){ 
    if(a[t]>0){
      int at=a[t];
      a[t]=0;
      ans+=at;
      return make_tuple(at,0,1);
    }
    return make_tuple(0,a[t],1);
  }
  vector<pair<int,int>> ch;
  int chmin=0,mini=-1,nums=0;
  for(int i=0;i<(int)g[t].size();i++){
    if(g[t][i]==p) continue;
    auto [at,ca,num]=dfs(g[t][i],t);
    
    if(at>0) a[t]+=at;
    if(chmin>ca){
      chmin=ca;
      mini=i;
    }
    ch.emplace_back(ca,num);
    nums+=num;
  }
  int chn=(int)ch.size();
  int at=0;
  if(mini!=-1){
    ans+=(-chmin);
    if(t!=0){
      at+=(-chmin);
      a[t]+=chmin*(chn+1);
    }else{
      a[t]+=chmin*chn;
    }
    for(int i=0;i<chn;i++){
      if(i==mini) continue;
      auto [ca,num]=ch[i];
      ans+=((ca-chmin)*num);
      a[t]+=(ca-chmin);
    }
  }
  
  if(a[t]>0){
    at+=a[t];
    ans+=a[t];
    ans+=(a[t]*nums);
    a[t]=0;
  }
  return make_tuple(at,a[t],nums+1);
}


int main() {

  int n;
  cin >> n;
  int u,v;
  for(int i=0;i<n-1;i++){
    cin >> u >> v;
    u--;v--;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  for(int i=0;i<n;i++) cin >> a[i];
  for(int i=0;i<n;i++){
    cin >> u;
    a[i]-=u;
  }

  auto [at,ca,num]=dfs(0,-1);
  cout << ans << endl;
  //cout << at << " " << ca << " " << num << endl;
}
accuracy: 0.08695652173913043
time_ms: 30
memory_kb: 7728
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;

#define rep(i, m, n) for(int(i) = (int)(m); i < (int)(n); ++i)
#define rep2(i, m, n) for(int(i) = (int)(n)-1; i >= (int)(m); --i)
#define REP(i, n) rep(i, 0, n)
#define REP2(i, n) rep2(i, 0, n)
#define all(hoge) (hoge).begin(), (hoge).end()
#define en '\n'
using ll = long long;
using ull = unsigned long long;
template <class T>
using vec = vector<T>;
template <class T>
using vvec = vector<vec<T>>;
typedef pair<ll, ll> P;
using tp = tuple<ll, ll, ll>;
constexpr long long INF = 1LL << 60;
constexpr int INF_INT = 1 << 25;
//constexpr long long MOD = (ll)1e9 + 7;
constexpr long long MOD = 998244353LL;
using ld = long double;
static const ld pi = 3.141592653589793L;
typedef vector<ll> Array;
typedef vector<Array> Matrix;

template <class T>
inline bool chmin(T &a, T b) {
    if(a > b) {
        a = b;
        return true;
    }
    return false;
}
template <class T>
inline bool chmax(T &a, T b) {
    if(a < b) {
        a = b;
        return true;
    }
    return false;
}

//グラフ関連
struct Edge {
    ll to, cap, rev;
    Edge(ll _to, ll _cap, ll _rev) {
        to = _to;
        cap = _cap;
        rev = _rev;
    }
};
typedef vector<Edge> Edges;
typedef vector<Edges> Graph;

void add_edge(Graph &G, ll from, ll to, ll cap, bool revFlag, ll revCap) {
    G[from].push_back(Edge(to, cap, (ll)G[to].size()));
    if(revFlag)
        G[to].push_back(Edge(from, revCap, (ll)G[from].size() - 1));
}

int sz[101010];
int cost[101010];
int diff[101010];
void solve() {
    ll n;
    cin >> n;
    Graph g(n);
    REP(i, n - 1) {
        ll u, v;
        cin >> u >> v;
        u--;
        v--;
        add_edge(g, u, v, 1, true, 1);
    }

    vec<ll> a(n), b(n);
    REP(i, n) {
        cin >> a[i];
    }
    REP(i, n) {
        cin >> b[i];
    }

    auto dfs = [&](auto &&self, int v, int p) -> void {
        sz[v] = 1;
        int ma = -INF_INT;
        for(auto e : g[v]) {
            if(e.to == p)
                continue;
            self(self, e.to, v);
            sz[v] += sz[e.to];
            chmax(ma, diff[e.to]);
        }

        diff[v] = b[v] - a[v];
        if(ma != -INF_INT)
            cost[v] = max(ma, 0);
        else
            cost[v] += max(a[v] - b[v], 0LL);

        for(auto e : g[v]) {
            if(e.to == p)
                continue;
            if(ma >= 0 and diff[e.to] <= ma) {
                cost[v] += max(0, ma - diff[e.to]) * sz[e.to]; //余計に渡したぶんを回収
            }
            diff[v] += diff[e.to]; //不足分を引かれる
            cost[v] += cost[e.to];
        }
        //cout << v << " " << cost[v] << " " << diff[v] << " " << sz[v] << en;
    };

    dfs(dfs, 0, -1);
    cout << cost[0] << en;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    /*
    ll t;
    cin >> t;
    while(t--)*/
    solve();

    return 0;
}
accuracy: 0.08695652173913043
time_ms: 20
memory_kb: 10096
final_rank: 18

code_snippet: #include <bits/stdc++.h>
using namespace std;

#define rep(i, m, n) for(int(i) = (int)(m); i < (int)(n); ++i)
#define rep2(i, m, n) for(int(i) = (int)(n)-1; i >= (int)(m); --i)
#define REP(i, n) rep(i, 0, n)
#define REP2(i, n) rep2(i, 0, n)
#define all(hoge) (hoge).begin(), (hoge).end()
#define en '\n'
using ll = long long;
using ull = unsigned long long;
template <class T>
using vec = vector<T>;
template <class T>
using vvec = vector<vec<T>>;
typedef pair<ll, ll> P;
using tp = tuple<ll, ll, ll>;
constexpr long long INF = 1LL << 60;
constexpr int INF_INT = 1 << 25;
//constexpr long long MOD = (ll)1e9 + 7;
constexpr long long MOD = 998244353LL;
using ld = long double;
static const ld pi = 3.141592653589793L;
typedef vector<ll> Array;
typedef vector<Array> Matrix;

template <class T>
inline bool chmin(T &a, T b) {
    if(a > b) {
        a = b;
        return true;
    }
    return false;
}
template <class T>
inline bool chmax(T &a, T b) {
    if(a < b) {
        a = b;
        return true;
    }
    return false;
}

//グラフ関連
struct Edge {
    ll to, cap, rev;
    Edge(ll _to, ll _cap, ll _rev) {
        to = _to;
        cap = _cap;
        rev = _rev;
    }
};
typedef vector<Edge> Edges;
typedef vector<Edges> Graph;

void add_edge(Graph &G, ll from, ll to, ll cap, bool revFlag, ll revCap) {
    G[from].push_back(Edge(to, cap, (ll)G[to].size()));
    if(revFlag)
        G[to].push_back(Edge(from, revCap, (ll)G[from].size() - 1));
}

int sz[101010];
int cost[101010];
int diff[101010];
void solve() {
    ll n;
    cin >> n;
    Graph g(n);
    REP(i, n - 1) {
        ll u, v;
        cin >> u >> v;
        u--;
        v--;
        add_edge(g, u, v, 1, true, 1);
    }

    vec<ll> a(n), b(n);
    REP(i, n) {
        cin >> a[i];
    }
    REP(i, n) {
        cin >> b[i];
    }

    auto dfs = [&](auto &&self, int v, int p) -> void {
        sz[v] = 1;
        int ma = -INF_INT;
        for(auto e : g[v]) {
            if(e.to == p)
                continue;
            self(self, e.to, v);
            sz[v] += sz[e.to];
            chmax(ma, diff[e.to]);
        }

        diff[v] = b[v] - a[v];
        if(ma != -INF_INT)
            cost[v] = max(ma, 0);
        else
            cost[v] += max(a[v] - b[v], 0LL);

        for(auto e : g[v]) {
            if(e.to == p)
                continue;
            if(diff[e.to] <= ma) {
                cost[v] += max(0, ma - diff[e.to]) * sz[e.to]; //余計に渡したぶんを回収
            }
            diff[v] += diff[e.to]; //不足分を引かれる
            cost[v] += cost[e.to];
        }
        //cout << v << " " << cost[v] << " " << diff[v] << " " << sz[v] << en;
    };

    dfs(dfs, 0, -1);
    cout << cost[0] << en;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    /*
    ll t;
    cin >> t;
    while(t--)*/
    solve();

    return 0;
}
accuracy: 0.08695652173913043
time_ms: 10
memory_kb: 10052
final_rank: 17

code_snippet: // verification-helper: PROBLEM http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=3142

#include<bits/stdc++.h>
using namespace std;

#define call_from_test

#ifndef call_from_test
#include <bits/stdc++.h>
using namespace std;
#endif
//BEGIN CUT HERE
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
//END CUT HERE
#ifndef call_from_test
signed main(){
  return 0;
}
#endif

#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
#endif
//BEGIN CUT HERE
template<typename F>
struct FixPoint : F{
  FixPoint(F&& f):F(forward<F>(f)){}
  template<typename... Args>
  decltype(auto) operator()(Args&&... args) const{
    return F::operator()(*this,forward<Args>(args)...);
  }
};
template<typename F>
inline decltype(auto) MFP(F&& f){
  return FixPoint<F>{forward<F>(f)};
}
//END CUT HERE
#ifndef call_from_test
//INSERT ABOVE HERE
signed main(){
  return 0;
}
#endif

#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
#endif
//BEGIN CUT HERE
struct Centroid{
  vector<int> sz,dead;
  vector< vector<int> > G;
  Centroid(){}
  Centroid(int n):sz(n,1),dead(n,0),G(n){}

  void add_edge(int u,int v){
    G[u].emplace_back(v);
    G[v].emplace_back(u);
  }

  int dfs(int v,int p){
    sz[v]=1;
    for(int u:G[v])
      if(u!=p&&!dead[u]) sz[v]+=dfs(u,v);
    return sz[v];
  }

  void find(int v,int p,int tmp,vector<int> &cs) {
    int ok=1;
    for (int u:G[v]){
      if(u==p||dead[u]) continue;
      find(u,v,tmp,cs);
      ok&=(sz[u]<=tmp/2);
    }
    ok&=(tmp-sz[v]<=tmp/2);
    if(ok) cs.emplace_back(v);
  }

  vector<int> build(int r) {
    int tmp=dfs(r,-1);
    vector<int> cs;
    find(r,-1,tmp,cs);
    return cs;
  }

  const vector<int>& operator[](int k)const{return G[k];}
  void disable(int v){dead[v]=1;}
  void  enable(int v){dead[v]=0;}
  int alive(int v){return !dead[v];}
};
//END CUT HERE
#ifndef call_from_test
signed main(){
  return 0;
}
#endif

#undef call_from_test

signed main(){
  cin.tie(0);
  ios::sync_with_stdio(0);
  using ll = long long;

  int n;
  cin>>n;
  Centroid G(n);
  for(int i=1;i<n;i++){
    int u,v;
    cin>>u>>v;
    u--;v--;
    G.add_edge(u,v);
  }

  vector<ll> as(n),bs(n);
  for(int i=0;i<n;i++) cin>>as[i];
  for(int i=0;i<n;i++) cin>>bs[i];

  using P = pair<int, ll>;
  vector<vector<P>> H(n);
  MFP([&](auto dfs,int v,int p)->ll{
    ll res=as[v]-bs[v];
    for(int u:G[v]){
      if(u==p) continue;
      ll tmp=dfs(u,v);
      H[u].emplace_back(v,-tmp);
      H[v].emplace_back(u,+tmp);
      res+=tmp;
    }
    return res;
  })(0,-1);

  vector<ll> dp(n,0);
  queue<int> que;
  que.emplace(G.build(0)[0]);

  vector<ll> tmp(n);
  while(!que.empty()){
    int r=que.front();que.pop();

    for(int t=0;t<2;t++){
      ll res=0;
      for(auto ch:H[r]){
        int c=ch.first;
        if(!G.alive(c)) continue;

        // calc cost
        MFP([&](auto dfs,int v,int p,ll d)->void{
          chmin(dp[v],-d+res);
          for(auto[u,w]:H[v]){
            if(u==p) continue;
            if(!G.alive(u)) continue;
            dfs(u,v,d+w);
          }
        })(c,r,ch.second);

        // update cost
        MFP([&](auto dfs,int v,int p,ll d)->void{
          chmin(res,d);
          for(auto[u,w]:H[v]){
            if(u==p) continue;
            if(!G.alive(u)) continue;
            dfs(u,v,d+w);
          }
        })(c,r,ch.second);
      }
      chmin(dp[r],res);
      reverse(H[r].begin(),H[r].end());
    }

    G.disable(r);
    for(int c:G.G[r])
      if(G.alive(c))
        que.emplace(G.build(c)[0]);
  }

  ll ans=0;
  for(ll x:dp) ans+=x;
  cout<<-ans<<endl;
  return 0;
}
accuracy: 1
time_ms: 230
memory_kb: 31264
final_rank: 10

code_snippet: // verification-helper: PROBLEM http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=3142

#include<bits/stdc++.h>
using namespace std;

#define call_from_test

#ifndef call_from_test
#include <bits/stdc++.h>
using namespace std;
#endif
//BEGIN CUT HERE
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
//END CUT HERE
#ifndef call_from_test
signed main(){
  return 0;
}
#endif

#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
#endif
//BEGIN CUT HERE
template<typename F>
struct FixPoint : F{
  FixPoint(F&& f):F(forward<F>(f)){}
  template<typename... Args>
  decltype(auto) operator()(Args&&... args) const{
    return F::operator()(*this,forward<Args>(args)...);
  }
};
template<typename F>
inline decltype(auto) MFP(F&& f){
  return FixPoint<F>{forward<F>(f)};
}
//END CUT HERE
#ifndef call_from_test
//INSERT ABOVE HERE
signed main(){
  return 0;
}
#endif

#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
#endif
//BEGIN CUT HERE
struct Centroid{
  vector<int> sz,dead;
  vector< vector<int> > G;
  Centroid(){}
  Centroid(int n):sz(n,1),dead(n,0),G(n){}

  void add_edge(int u,int v){
    G[u].emplace_back(v);
    G[v].emplace_back(u);
  }

  int dfs(int v,int p){
    sz[v]=1;
    for(int u:G[v])
      if(u!=p&&!dead[u]) sz[v]+=dfs(u,v);
    return sz[v];
  }

  void find(int v,int p,int tmp,vector<int> &cs) {
    int ok=1;
    for (int u:G[v]){
      if(u==p||dead[u]) continue;
      find(u,v,tmp,cs);
      ok&=(sz[u]<=tmp/2);
    }
    ok&=(tmp-sz[v]<=tmp/2);
    if(ok) cs.emplace_back(v);
  }

  vector<int> build(int r) {
    int tmp=dfs(r,-1);
    vector<int> cs;
    find(r,-1,tmp,cs);
    return cs;
  }

  const vector<int>& operator[](int k)const{return G[k];}
  void disable(int v){dead[v]=1;}
  void  enable(int v){dead[v]=0;}
  int alive(int v){return !dead[v];}
};
//END CUT HERE
#ifndef call_from_test
signed main(){
  return 0;
}
#endif

#undef call_from_test

signed main(){
  cin.tie(0);
  ios::sync_with_stdio(0);
  using ll = long long;

  int n;
  cin>>n;
  Centroid G(n);
  for(int i=1;i<n;i++){
    int u,v;
    cin>>u>>v;
    u--;v--;
    G.add_edge(u,v);
  }

  vector<ll> as(n),bs(n);
  for(int i=0;i<n;i++) cin>>as[i];
  for(int i=0;i<n;i++) cin>>bs[i];

  using P = pair<int, ll>;
  vector<vector<P>> H(n);
  MFP([&](auto dfs,int v,int p)->ll{
        ll res=as[v]-bs[v];
        for(int u:G.G[v]){
          if(u==p) continue;
          ll tmp=dfs(u,v);
          H[u].emplace_back(v,-tmp);
          H[v].emplace_back(u,+tmp);
          res+=tmp;
        }
        return res;
      })(0,-1);

  vector<ll> dp(n,0);
  queue<int> que;
  que.emplace(G.build(0)[0]);

  vector<ll> tmp(n);
  while(!que.empty()){
    int r=que.front();que.pop();

    for(int t=0;t<2;t++){
      ll res=0;
      for(auto ch:H[r]){
        int c=ch.first;
        if(!G.alive(c)) continue;

        // calc cost
        MFP([&](auto dfs,int v,int p,ll d)->void{
              chmin(dp[v],-d+res);
              for(auto[u,w]:H[v]){
                if(u==p) continue;
                if(!G.alive(u)) continue;
                dfs(u,v,d+w);
              }
            })(c,r,ch.second);

        // update cost
        MFP([&](auto dfs,int v,int p,ll d)->void{
              chmin(res,d);
              for(auto[u,w]:H[v]){
                if(u==p) continue;
                if(!G.alive(u)) continue;
                dfs(u,v,d+w);
              }
            })(c,r,ch.second);
      }
      chmin(dp[r],res);
      reverse(H[r].begin(),H[r].end());
    }

    G.disable(r);
    for(int c:G.G[r])
      if(G.alive(c))
        que.emplace(G.build(c)[0]);
  }

  ll ans=0;
  for(int x:dp) ans+=x;
  cout<<-ans<<endl;
  return 0;
}
accuracy: 0.2608695652173913
time_ms: 240
memory_kb: 26180
final_rank: 12

code_snippet: #include <bits/stdc++.h>
using namespace std;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
using Int = long long;
const char newl = '\n';


template<typename F>
struct FixPoint : F{
  FixPoint(F&& f):F(forward<F>(f)){}
  template<typename... Args>
  decltype(auto) operator()(Args&&... args) const{
    return F::operator()(*this,forward<Args>(args)...);
  }
};
template<typename F>
inline decltype(auto) MFP(F&& f){
  return FixPoint<F>{forward<F>(f)};
}


struct Centroid{
  vector<Int> sz,dead;
  vector< vector<Int> > G;
  Centroid(){}
  Centroid(Int n):sz(n,1),dead(n,0),G(n){}

  void add_edge(Int u,Int v){
    G[u].emplace_back(v);
    G[v].emplace_back(u);
  }

  Int dfs(Int v,Int p){
    sz[v]=1;
    for(Int u:G[v])
      if(u!=p&&!dead[u]) sz[v]+=dfs(u,v);
    return sz[v];
  }

  void find(Int v,Int p,Int tmp,vector<Int> &cs) {
    Int ok=1;
    for (Int u:G[v]){
      if(u==p||dead[u]) continue;
      find(u,v,tmp,cs);
      ok&=(sz[u]<=tmp/2);
    }
    ok&=(tmp-sz[v]<=tmp/2);
    if(ok) cs.emplace_back(v);
  }

  vector<Int> build(Int r) {
    Int tmp=dfs(r,-1);
    vector<Int> cs;
    find(r,-1,tmp,cs);
    return cs;
  }

  void disable(Int v){dead[v]=1;}
  void  enable(Int v){dead[v]=0;}
  Int alive(Int v){return !dead[v];}
};

//INSERT ABOVE HERE
signed main(){
  cin.tie(0);
  ios::sync_with_stdio(0);

  Int n;
  cin>>n;
  Centroid G(n);
  for(Int i=1;i<n;i++){
    Int u,v;
    cin>>u>>v;
    u--;v--;
    G.add_edge(u,v);
  }

  vector<Int> as(n),bs(n);
  for(Int i=0;i<n;i++) cin>>as[i];
  for(Int i=0;i<n;i++) cin>>bs[i];

  using P = pair<Int, Int>;
  vector<vector<P>> H(n);
  MFP([&](auto dfs,Int v,Int p)->Int{
        Int res=as[v]-bs[v];
        for(Int u:G.G[v]){
          if(u==p) continue;
          Int tmp=dfs(u,v);
          //cout<<u+1<<" "<<v+1<<":"<<-tmp<<endl;
          //cout<<v+1<<" "<<u+1<<":"<<+tmp<<endl;
          H[u].emplace_back(v,-tmp);
          H[v].emplace_back(u,+tmp);
          res+=tmp;
        }
        return res;
      })(0,-1);

  vector<Int> dp(n,0);
  queue<Int> que;
  que.emplace(G.build(0)[0]);

  vector<Int> tmp(n);
  while(!que.empty()){
    Int r=que.front();que.pop();

    for(Int t=0;t<2;t++){
      Int res=0;
      for(auto ch:H[r]){
        Int c=ch.first;
        if(!G.alive(c)) continue;

        // calc cost
        MFP([&](auto dfs,Int v,Int p,Int d)->void{
              // cout<<r+1<<":"<<v+1<<" "<<d<<endl;
              chmin(dp[v],-d+res);
              for(auto e:H[v]){
                Int u=e.first,w=e.second;
                if(u==p) continue;
                if(!G.alive(u)) continue;
                dfs(u,v,d+w);
              }
            })(c,r,ch.second);

        // update cost
        MFP([&](auto dfs,Int v,Int p,Int d)->void{
              chmin(res,d);
              for(auto e:H[v]){
                Int u=e.first,w=e.second;
                if(u==p) continue;
                if(!G.alive(u)) continue;
                dfs(u,v,d+w);
              }
            })(c,r,ch.second);
      }
      chmin(dp[r],res);
      reverse(H[r].begin(),H[r].end());
    }

    G.disable(r);
    for(Int c:G.G[r])
      if(G.alive(c))
        que.emplace(G.build(c)[0]);
  }
  // for(Int x:dp) cout<<x<<endl;

  Int ans=0;
  for(Int x:dp) ans+=x;
  cout<<-ans<<endl;
  return 0;
}
accuracy: 1
time_ms: 290
memory_kb: 32024
final_rank: 11

code_snippet: #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 1000000000000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


#define SIZE 100005


ll V;
vector<int> G[SIZE];
ll A[SIZE],B[SIZE],diff[SIZE];
ll COUNT[SIZE];

void dfs(int node_id,int pre){

	diff[node_id] = A[node_id]-B[node_id];

	for(int i = 0; i < G[node_id].size(); i++){

		int child = G[node_id][i];
		if(child == pre)continue;

		dfs(child,node_id);
		diff[node_id] += diff[child];
	}
}

void dfs2(int node_id,int pre){

	for(int i = 0; i < G[node_id].size(); i++){

		int child = G[node_id][i];

		if(child == pre){
			COUNT[node_id] = COUNT[pre]+diff[node_id];
			break;
		}
	}

	for(int i = 0; i < G[node_id].size(); i++){

		int child = G[node_id][i];
		if(child == pre)continue;

		dfs2(child,node_id);
	}
}


int main(){

	scanf("%lld",&V);

	int from,to;
	for(ll i = 0; i < V-1; i++){

		scanf("%d %d",&from,&to);
		from--;
		to--;

		G[from].push_back(to);
		G[to].push_back(from);
	}
	for(ll i = 0; i < V; i++){

		scanf("%lld",&A[i]);
	}
	for(ll i = 0; i < V; i++){

		scanf("%lld",&B[i]);
	}

	dfs(0,-1);

	COUNT[0] = 0;
	dfs2(0,-1);

	ll ans = 0;
	ll minimum = HUGE_NUM;

	for(int i = 0; i < V; i++){

		ans += COUNT[i];
		minimum = min(minimum,COUNT[i]);
	}

	ans -= V*minimum;

	printf("%lld\n",ans);

	return 0;
}
accuracy: 1
time_ms: 50
memory_kb: 17664
final_rank: 2

code_snippet: #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 1000000000000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


#define SIZE 100005


int V;
ll ans;
vector<int> G[SIZE];
ll A[SIZE],B[SIZE],diff[SIZE];

void dfs(int node_id,int pre){

	ll sum = 0;

	for(int i = 0; i < G[node_id].size(); i++){

		int child = G[node_id][i];
		if(child == pre)continue;

		dfs(child,node_id);
		sum += diff[child];
	}

	ll tmp = A[node_id]+sum-B[node_id];
	ans += abs(tmp);
}


int main(){

	scanf("%d",&V);

	int from,to;
	for(int i = 0; i < V-1; i++){

		scanf("%d %d",&from,&to);
		from--;
		to--;

		G[from].push_back(to);
		G[to].push_back(from);
	}
	for(int i = 0; i < V; i++){

		scanf("%lld",&A[i]);
	}
	for(int i = 0; i < V; i++){

		scanf("%lld",&B[i]);
	}

	ans = 0;

	dfs(0,-1);

	printf("%lld\n",ans/2);

	return 0;
}
accuracy: 0.08695652173913043
time_ms: 20
memory_kb: 8520
final_rank: 14

code_snippet: #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 1000000000000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


#define SIZE 100005


int V;
int ans;
vector<int> G[SIZE];
int A[SIZE],B[SIZE],diff[SIZE];

void dfs(int node_id,int pre){

	int sum = 0;

	for(int i = 0; i < G[node_id].size(); i++){

		int child = G[node_id][i];
		if(child == pre)continue;

		dfs(child,node_id);
		sum += diff[child];
	}

	int tmp = A[node_id]+sum-B[node_id];
	ans += abs(tmp);
}


int main(){

	scanf("%d",&V);

	int from,to;
	for(int i = 0; i < V-1; i++){

		scanf("%d %d",&from,&to);
		from--;
		to--;

		G[from].push_back(to);
		G[to].push_back(from);
	}
	for(int i = 0; i < V; i++){

		scanf("%d",&A[i]);
	}
	for(int i = 0; i < V; i++){

		scanf("%d",&B[i]);
	}

	ans = 0;

	dfs(0,-1);

	printf("%d\n",ans/2);

	return 0;
}
accuracy: 0.08695652173913043
time_ms: 20
memory_kb: 8048
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
typedef double db;
mt19937 mrand(random_device{}()); 
const ll mod=998244353;
int rnd(int x) { return mrand() % x;}
ll powmod(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
ll gcd(ll a,ll b) { return b?gcd(b,a%b):a;}
// head

const int N=201000;
int n,a[N],b[N],u,v;
VI e[N];
ll ret[N];

void dfs(int u,int f) {
	for (auto v:e[u]) {
		if (v==f) continue;
		dfs(v,u);
		a[u]+=a[v];
		b[u]+=b[v];
	}
}

void dfs2(int u,int f) {
	for (auto v:e[u]) {
		if (v==f) continue;
		ret[v]=ret[u]+a[v]-b[v];
		dfs2(v,u);
	}
}

int main() {
	scanf("%d",&n);
	rep(i,1,n) {
		scanf("%d%d",&u,&v);
		e[u].pb(v);
		e[v].pb(u);
	}
	rep(i,1,n+1) scanf("%d",a+i);
	rep(i,1,n+1) scanf("%d",b+i);
	dfs(1,0);
	dfs2(1,0);
	ll x=*min_element(ret+1,ret+n+1);
	ll ans=0;
	rep(i,1,n+1) ans+=ret[i]-x;
	printf("%lld\n",ans);
}
accuracy: 1
time_ms: 50
memory_kb: 18448
final_rank: 3

code_snippet: #include<bits/stdc++.h>
using namespace std;
#ifndef ONLINE_JUDGE
#define dbg(x...) do { cout << "\033[32;1m " << #x << " -> "; err(x); } while (0)
void err() { cout << "\033[39;0m" << endl; }
template<template<typename...> class T, typename t, typename... A>
void err(T<t> a, A... x) { for (auto v: a) cout << v << ' '; err(x...); }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }
#else
#define dbg(...)
#endif
typedef long long ll;
typedef pair<int,int> pi;
typedef vector<int> vi;
template<class T> using vc=vector<T>;
template<class T> using vvc=vc<vc<T>>;
template<class T> void mkuni(vector<T>&v)
{
    sort(v.begin(),v.end());
    v.erase(unique(v.begin(),v.end()),v.end());
}
ll rand_int(ll l, ll r) //[l, r]
{
    static mt19937_64 gen(chrono::steady_clock::now().time_since_epoch().count());
    return uniform_int_distribution<ll>(l, r)(gen);
}
template<class T>
void print(T x,int suc=1)
{
    cout<<x;
    if(suc==1) cout<<'\n';
    else cout<<' ';
}
template<class T>
void print(const vector<T>&v,int suc=1)
{
    for(int i=0;i<v.size();i++)
    print(v[i],i==(int)(v.size())-1?suc:2);
}
const int maxn=1e5+7;
vi G[maxn];
int a[maxn],b[maxn];
int sum[maxn];
ll ans=0;
void dfs(int u,int fa=-1)
{
    sum[u]=b[u]-a[u];
    for(auto v:G[u])if(v!=fa)
    {
        dfs(v,u);
        sum[u]+=sum[v];
    }
}
ll k[maxn];
void dfs2(int u,int fa=-1,ll cur=0)
{
    k[u]=cur;
    ans=min(ans,k[u]);
    for(auto v:G[u])if(v!=fa)
        dfs2(v,u,cur-sum[v]);
}
int main()
{
    int n;
    cin>>n;
    for(int i=1,u,v;i<n;i++)
    {
        cin>>u>>v;
        G[u].push_back(v);
        G[v].push_back(u);
    }
    for(int i=0;i<n;i++) cin>>a[i+1];
    for(int i=0;i<n;i++) cin>>b[i+1];
    dfs(1);
    dfs2(1);
    //dbg(ans);
    ll op=0;
    for(int i=1;i<=n;i++)
    {
        //dbg(k[i]);
        op+=k[i];
    }
    op+=-n*ans;
    print(op);
}
accuracy: 1
time_ms: 100
memory_kb: 16268
final_rank: 7

code_snippet: #include<bits/stdc++.h>
using namespace std;
#ifndef ONLINE_JUDGE
#define dbg(x...) do { cout << "\033[32;1m " << #x << " -> "; err(x); } while (0)
void err() { cout << "\033[39;0m" << endl; }
template<template<typename...> class T, typename t, typename... A>
void err(T<t> a, A... x) { for (auto v: a) cout << v << ' '; err(x...); }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }
#else
#define dbg(...)
#endif
typedef long long ll;
typedef pair<int,int> pi;
typedef vector<int> vi;
template<class T> using vc=vector<T>;
template<class T> using vvc=vc<vc<T>>;
template<class T> void mkuni(vector<T>&v)
{
    sort(v.begin(),v.end());
    v.erase(unique(v.begin(),v.end()),v.end());
}
ll rand_int(ll l, ll r) //[l, r]
{
    static mt19937_64 gen(chrono::steady_clock::now().time_since_epoch().count());
    return uniform_int_distribution<ll>(l, r)(gen);
}
template<class T>
void print(T x,int suc=1)
{
    cout<<x;
    if(suc==1) cout<<'\n';
    else cout<<' ';
}
template<class T>
void print(const vector<T>&v,int suc=1)
{
    for(int i=0;i<v.size();i++)
    print(v[i],i==(int)(v.size())-1?suc:2);
}
const int maxn=1e5+7;
vi G[maxn];
int a[maxn],b[maxn];
int sum[maxn];
int ans=0x3f3f3f3f;
void dfs(int u,int fa=-1)
{
    sum[u]=b[u]-a[u];
    for(auto v:G[u])if(v!=fa)
    {
        dfs(v,u);
        sum[u]+=sum[v];
    }
}
int k[maxn];
void dfs2(int u,int fa=-1,int cur=0)
{
    k[u]=cur;
    ans=min(ans,k[u]);
    for(auto v:G[u])if(v!=fa)
        dfs2(v,u,cur-sum[v]);
}
int main()
{
    int n;
    cin>>n;
    for(int i=1,u,v;i<n;i++)
    {
        cin>>u>>v;
        G[u].push_back(v);
        G[v].push_back(u);
    }
    for(int i=0;i<n;i++) cin>>a[i+1];
    for(int i=0;i<n;i++) cin>>b[i+1];
    dfs(1);
    dfs2(1);
    //dbg(ans);
    int op=0;
    for(int i=1;i<=n;i++)
    {
        //dbg(k[i]);
        op+=k[i];
    }
    op+=-n*ans;
    print(op);
}
accuracy: 0.08695652173913043
time_ms: 50
memory_kb: 8324
final_rank: 19

code_snippet: #include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cmath>
#include <map>
#include <queue>
#include <iomanip>
#include <set>
#include <tuple>
#define mkp make_pair
#define mkt make_tuple
#define rep(i,n) for(int i = 0; i < (n); ++i)
using namespace std;
typedef long long ll;
const ll MOD=1e9+7;
template<class T> void chmin(T &a,const T &b){if(a>b) a=b;}
template<class T> void chmax(T &a,const T &b){if(a<b) a=b;}

vector<vector<int>> g;
vector<ll> A,B;

ll ans;
vector<int> size;
vector<ll> dp;

void sizedfs(int now,int par){
    size[now]=1;
    for(auto nex:g[now]) if(nex!=par){
        sizedfs(nex,now);
        size[now]+=size[nex];
    }
}

void dfs(int now,int par){
    ll ma=0;
    for(auto nex:g[now]) if(nex!=par){
        dfs(nex,now);
        chmax(ma,-dp[nex]);
    }
    ans+=ma;
    dp[now]-=g[now].size()*ma;
    if(par!=-1) dp[par]+=ma;
    for(auto nex:g[now]) if(nex!=par){
        dp[nex]+=ma;
        ans+=dp[nex]*size[nex];
        dp[now]+=dp[nex];
        dp[nex]=0;
    }

    if(dp[now]>0){
        ans+=dp[now]*size[now];
        if(par!=-1) dp[par]+=dp[now];
        dp[now]=0;
    }
}


int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);

  int N;
  cin>>N;
  g.resize(N);
  rep(i,N-1){
      int a,b;
      cin>>a>>b;
      a--;b--;
      g[a].push_back(b);
      g[b].push_back(a);
  }
  A.resize(N);
  rep(i,N) cin>>A[i];
  B.resize(N);
  rep(i,N) cin>>B[i];

  int root=0;
  rep(i,N) if(g[i].size()==1) root=i;
  size.resize(N);
  sizedfs(root,-1);

  dp.resize(N);
  rep(i,N) dp[i]=A[i]-B[i];
  dfs(root,-1);

  cout<<ans<<endl;

  return 0;
}
accuracy: 1
time_ms: 50
memory_kb: 18912
final_rank: 4

code_snippet: #include <bits/stdc++.h>
// created [2020/03/20] 14:42:56
#pragma GCC diagnostic ignored "-Wsign-compare"
#pragma GCC diagnostic ignored "-Wsign-conversion"

using i32   = int32_t;
using i64   = int64_t;
using u32   = uint32_t;
using u64   = uint64_t;
using uint  = unsigned int;
using usize = std::size_t;
using ll    = long long;
using ull   = unsigned long long;
using ld    = long double;
template<typename T, usize n>
using arr = T (&)[n];
template<typename T, usize n>
using c_arr = const T (&)[n];
template<typename T>
using max_heap = std::priority_queue<T>;
template<typename T>
using min_heap = std::priority_queue<T, std::vector<T>, std::greater<T>>;
template<typename T> constexpr T popcount(const T u) { return u ? static_cast<T>(__builtin_popcountll(static_cast<u64>(u))) : static_cast<T>(0); }
template<typename T> constexpr T log2p1(const T u) { return u ? static_cast<T>(64 - __builtin_clzll(static_cast<u64>(u))) : static_cast<T>(0); }
template<typename T> constexpr T msbp1(const T u) { return log2p1(u); }
template<typename T> constexpr T lsbp1(const T u) { return __builtin_ffsll(u); }
template<typename T> constexpr T clog(const T u) { return u ? log2p1(u - 1) : static_cast<T>(u); }
template<typename T> constexpr bool ispow2(const T u) { return u and (static_cast<u64>(u) & static_cast<u64>(u - 1)) == 0; }
template<typename T> constexpr T ceil2(const T u) { return static_cast<T>(1) << clog(u); }
template<typename T> constexpr T floor2(const T u) { return u == 0 ? static_cast<T>(0) : static_cast<T>(1) << (log2p1(u) - 1); }
template<typename T> constexpr bool btest(const T mask, const usize ind) { return static_cast<bool>((static_cast<u64>(mask) >> ind) & static_cast<u64>(1)); }
template<typename T> void bset(T& mask, const usize ind) { mask |= (static_cast<T>(1) << ind); }
template<typename T> void breset(T& mask, const usize ind) { mask &= ~(static_cast<T>(1) << ind); }
template<typename T> void bflip(T& mask, const usize ind) { mask ^= (static_cast<T>(1) << ind); }
template<typename T> void bset(T& mask, const usize ind, const bool b) { (b ? bset(mask, ind) : breset(mask, ind)); }
template<typename T> constexpr T bcut(const T mask, const usize ind) { return ind == 0 ? static_cast<T>(0) : static_cast<T>((static_cast<u64>(mask) << (64 - ind)) >> (64 - ind)); }
template<typename T> bool chmin(T& a, const T& b) { return (a > b ? a = b, true : false); }
template<typename T> bool chmax(T& a, const T& b) { return (a < b ? a = b, true : false); }
constexpr unsigned int mod                  = 1000000007;
template<typename T> constexpr T inf_v      = std::numeric_limits<T>::max() / 4;
template<typename Real> constexpr Real pi_v = Real{3.141592653589793238462643383279502884};
auto mfp = [](auto&& f) { return [=](auto&&... args) { return f(f, std::forward<decltype(args)>(args)...); }; };

template<typename T>
T in()
{
    T v;
    return std::cin >> v, v;
}
template<typename T, typename Uint, usize n, usize i>
T in_v(typename std::enable_if<(i == n), c_arr<Uint, n>>::type) { return in<T>(); }
template<typename T, typename Uint, usize n, usize i>
auto in_v(typename std::enable_if<(i < n), c_arr<Uint, n>>::type& szs)
{
    const usize s = (usize)szs[i];
    std::vector<decltype(in_v<T, Uint, n, i + 1>(szs))> ans(s);
    for (usize j = 0; j < s; j++) { ans[j] = in_v<T, Uint, n, i + 1>(szs); }
    return ans;
}
template<typename T, typename Uint, usize n>
auto in_v(c_arr<Uint, n> szs) { return in_v<T, Uint, n, 0>(szs); }
template<typename... Types>
auto in_t() { return std::tuple<std::decay_t<Types>...>{in<Types>()...}; }
struct io_init
{
    io_init()
    {
        std::cin.tie(nullptr), std::ios::sync_with_stdio(false);
        std::cout << std::fixed << std::setprecision(20);
    }
    void clear()
    {
        std::cin.tie(), std::ios::sync_with_stdio(true);
    }
} io_setting;

int out() { return 0; }
template<typename T>
int out(const T& v) { return std::cout << v, 0; }
template<typename T>
int out(const std::vector<T>& v)
{
    for (usize i = 0; i < v.size(); i++) {
        if (i > 0) { std::cout << ' '; }
        out(v[i]);
    }
    return 0;
}
template<typename T1, typename T2>
int out(const std::pair<T1, T2>& v) { return out(v.first), std::cout << ' ', out(v.second), 0; }
template<typename T, typename... Args>
int out(const T& v, const Args... args) { return out(v), std::cout << ' ', out(args...), 0; }
template<typename... Args>
int outln(const Args... args) { return out(args...), std::cout << '\n', 0; }
template<typename... Args>
int outel(const Args... args) { return out(args...), std::cout << std::endl, 0; }
#    define SHOW(...) static_cast<void>(0)
constexpr ull TEN(const usize n) { return n == 0 ? 1ULL : TEN(n - 1) * 10ULL; }

template<typename T, typename Uint, usize n, usize i>
auto make_v(typename std::enable_if<(i == n), c_arr<Uint, n>>::type, const T& v = T{}) { return v; }
template<typename T, typename Uint, usize n, usize i>
auto make_v(typename std::enable_if<(i < n), c_arr<Uint, n>>::type szs, const T& v = T{})
{
    const usize s = (usize)szs[i];
    return std::vector<decltype(make_v<T, Uint, n, i + 1>(szs, v))>(s, make_v<T, Uint, n, i + 1>(szs, v));
}
template<typename T, typename Uint, usize n>
auto make_v(c_arr<Uint, n> szs, const T& t = T{}) { return make_v<T, Uint, n, 0>(szs, t); }

template<typename Cost = usize>
struct edge
{
    using cost_type = Cost;
    usize u, v;
    Cost c;
    edge(const usize u, const usize v) : u{u}, v{v}, c{1} {}
    edge(const usize u, const usize v, const Cost& c) : u{u}, v{v}, c{c} {}
    operator usize() const { return v; }
    usize from() const { return u; }
    usize to() const { return v; }
    Cost cost() const { return c; }
    friend std::ostream& operator<<(std::ostream& os, const edge& e) { return os << e.u << "->" << e.v << ":" << e.c; }
};
template<typename Edge>
class base_graph
{
public:
    base_graph(const usize n) : v{n}, es(n), res(n) {}
    void add_edge(const usize u, const usize v, const bool bi = false)
    {
        es[u].emplace_back(u, v), res[v].emplace_back(v, u);
        if (bi) { es[v].emplace_back(v, u), res[u].emplace_back(u, v); }
    }
    template<typename Cost>
    void add_edge(const usize u, const usize v, const Cost& c, const bool bi = false)
    {
        es[u].emplace_back(u, v, c), res[v].emplace_back(v, u, c);
        if (bi) { es[v].emplace_back(v, u, c), res[u].emplace_back(u, v, c); }
    }
    std::vector<Edge>& operator[](const usize u) { return es[u]; }
    const std::vector<Edge>& operator[](const usize u) const { return es[u]; }
    std::vector<Edge>& from(const usize u) { return es[u]; }
    const std::vector<Edge>& from(const usize u) const { return es[u]; }
    std::vector<Edge>& to(const usize v) { return res[v]; }
    const std::vector<Edge>& to(const usize v) const { return res[v]; }
    usize size() const { return v; }
    friend std::ostream& operator<<(std::ostream& os, const base_graph& g)
    {
        for (usize i = 0; i < g.v; i++) {
            for (const auto& e : g.es[i]) { os << e << '\n'; }
        }
        return os;
    }

private:
    usize v;
    std::vector<std::vector<Edge>> es, res;
};
template<typename Edge>
using base_tree = base_graph<Edge>;
using graph     = base_graph<edge<>>;
using tree      = base_graph<edge<>>;
template<typename Cost>
using cost_graph = base_graph<edge<Cost>>;
template<typename Cost>
using cost_tree = base_graph<edge<Cost>>;
int main()
{
    auto N = in<int>();
    graph g(N);
    for (int i = 0; i < N - 1; i++) {
        const auto u = in<int>() - 1, v = in<int>() - 1;
        g.add_edge(u, v, true);
    }
    const auto as = in_v<ll>({N});
    const auto bs = in_v<ll>({N});
    std::vector<ll> cs(N);
    for (int i = 0; i < N; i++) { cs[i] = bs[i] - as[i]; }
    using pll = std::pair<ll, ll>;
    std::vector<ll> push(N);    // push[i]=b     ：頂点iをした回数はx+b
    std::vector<ll> need(N);    // need[i]=b     ：頂点par[i]を押す回数はx+b
    std::vector<pll> total(N);  // total[i]=<a,b>：頂点i以下を押した回数はax+b
    mfp([&](auto&& self, const int s, const int p) -> void {
        ll max = 0;
        for (const int to : g[s]) {
            if (to == p) { continue; }
            self(self, to, s);
            chmax(max, need[to]);
        }
        push[s] = max;
        need[s] = cs[s] + push[s] * g[s].size();
        ll ta = 1, tb = push[s];
        for (const int to : g[s]) {
            if (to == p) { continue; }
            const ll alpha = max - need[to];
            need[s] -= push[to] + alpha;
            ta += total[to].first, tb += total[to].second + total[to].first * alpha;
        }
        total[s] = {ta, tb};
    })(0, -1);
    outln(total[0].second);
    return 0;
}
accuracy: 1
time_ms: 80
memory_kb: 30720
final_rank: 9

code_snippet: #include <bits/stdc++.h>
// created [2020/03/20] 14:42:56
#pragma GCC diagnostic ignored "-Wsign-compare"
#pragma GCC diagnostic ignored "-Wsign-conversion"

using i32   = int32_t;
using i64   = int64_t;
using u32   = uint32_t;
using u64   = uint64_t;
using uint  = unsigned int;
using usize = std::size_t;
using ll    = long long;
using ull   = unsigned long long;
using ld    = long double;
template<typename T, usize n>
using arr = T (&)[n];
template<typename T, usize n>
using c_arr = const T (&)[n];
template<typename T>
using max_heap = std::priority_queue<T>;
template<typename T>
using min_heap = std::priority_queue<T, std::vector<T>, std::greater<T>>;
template<typename T> constexpr T popcount(const T u) { return u ? static_cast<T>(__builtin_popcountll(static_cast<u64>(u))) : static_cast<T>(0); }
template<typename T> constexpr T log2p1(const T u) { return u ? static_cast<T>(64 - __builtin_clzll(static_cast<u64>(u))) : static_cast<T>(0); }
template<typename T> constexpr T msbp1(const T u) { return log2p1(u); }
template<typename T> constexpr T lsbp1(const T u) { return __builtin_ffsll(u); }
template<typename T> constexpr T clog(const T u) { return u ? log2p1(u - 1) : static_cast<T>(u); }
template<typename T> constexpr bool ispow2(const T u) { return u and (static_cast<u64>(u) & static_cast<u64>(u - 1)) == 0; }
template<typename T> constexpr T ceil2(const T u) { return static_cast<T>(1) << clog(u); }
template<typename T> constexpr T floor2(const T u) { return u == 0 ? static_cast<T>(0) : static_cast<T>(1) << (log2p1(u) - 1); }
template<typename T> constexpr bool btest(const T mask, const usize ind) { return static_cast<bool>((static_cast<u64>(mask) >> ind) & static_cast<u64>(1)); }
template<typename T> void bset(T& mask, const usize ind) { mask |= (static_cast<T>(1) << ind); }
template<typename T> void breset(T& mask, const usize ind) { mask &= ~(static_cast<T>(1) << ind); }
template<typename T> void bflip(T& mask, const usize ind) { mask ^= (static_cast<T>(1) << ind); }
template<typename T> void bset(T& mask, const usize ind, const bool b) { (b ? bset(mask, ind) : breset(mask, ind)); }
template<typename T> constexpr T bcut(const T mask, const usize ind) { return ind == 0 ? static_cast<T>(0) : static_cast<T>((static_cast<u64>(mask) << (64 - ind)) >> (64 - ind)); }
template<typename T> bool chmin(T& a, const T& b) { return (a > b ? a = b, true : false); }
template<typename T> bool chmax(T& a, const T& b) { return (a < b ? a = b, true : false); }
constexpr unsigned int mod                  = 1000000007;
template<typename T> constexpr T inf_v      = std::numeric_limits<T>::max() / 4;
template<typename Real> constexpr Real pi_v = Real{3.141592653589793238462643383279502884};
auto mfp = [](auto&& f) { return [=](auto&&... args) { return f(f, std::forward<decltype(args)>(args)...); }; };

template<typename T>
T in()
{
    T v;
    return std::cin >> v, v;
}
template<typename T, typename Uint, usize n, usize i>
T in_v(typename std::enable_if<(i == n), c_arr<Uint, n>>::type) { return in<T>(); }
template<typename T, typename Uint, usize n, usize i>
auto in_v(typename std::enable_if<(i < n), c_arr<Uint, n>>::type& szs)
{
    const usize s = (usize)szs[i];
    std::vector<decltype(in_v<T, Uint, n, i + 1>(szs))> ans(s);
    for (usize j = 0; j < s; j++) { ans[j] = in_v<T, Uint, n, i + 1>(szs); }
    return ans;
}
template<typename T, typename Uint, usize n>
auto in_v(c_arr<Uint, n> szs) { return in_v<T, Uint, n, 0>(szs); }
template<typename... Types>
auto in_t() { return std::tuple<std::decay_t<Types>...>{in<Types>()...}; }
struct io_init
{
    io_init()
    {
        std::cin.tie(nullptr), std::ios::sync_with_stdio(false);
        std::cout << std::fixed << std::setprecision(20);
    }
    void clear()
    {
        std::cin.tie(), std::ios::sync_with_stdio(true);
    }
} io_setting;

int out() { return 0; }
template<typename T>
int out(const T& v) { return std::cout << v, 0; }
template<typename T>
int out(const std::vector<T>& v)
{
    for (usize i = 0; i < v.size(); i++) {
        if (i > 0) { std::cout << ' '; }
        out(v[i]);
    }
    return 0;
}
template<typename T1, typename T2>
int out(const std::pair<T1, T2>& v) { return out(v.first), std::cout << ' ', out(v.second), 0; }
template<typename T, typename... Args>
int out(const T& v, const Args... args) { return out(v), std::cout << ' ', out(args...), 0; }
template<typename... Args>
int outln(const Args... args) { return out(args...), std::cout << '\n', 0; }
template<typename... Args>
int outel(const Args... args) { return out(args...), std::cout << std::endl, 0; }
#    define SHOW(...) static_cast<void>(0)
constexpr ull TEN(const usize n) { return n == 0 ? 1ULL : TEN(n - 1) * 10ULL; }

template<typename T, typename Uint, usize n, usize i>
auto make_v(typename std::enable_if<(i == n), c_arr<Uint, n>>::type, const T& v = T{}) { return v; }
template<typename T, typename Uint, usize n, usize i>
auto make_v(typename std::enable_if<(i < n), c_arr<Uint, n>>::type szs, const T& v = T{})
{
    const usize s = (usize)szs[i];
    return std::vector<decltype(make_v<T, Uint, n, i + 1>(szs, v))>(s, make_v<T, Uint, n, i + 1>(szs, v));
}
template<typename T, typename Uint, usize n>
auto make_v(c_arr<Uint, n> szs, const T& t = T{}) { return make_v<T, Uint, n, 0>(szs, t); }

template<typename Cost = usize>
struct edge
{
    using cost_type = Cost;
    usize u, v;
    Cost c;
    edge(const usize u, const usize v) : u{u}, v{v}, c{1} {}
    edge(const usize u, const usize v, const Cost& c) : u{u}, v{v}, c{c} {}
    operator usize() const { return v; }
    usize from() const { return u; }
    usize to() const { return v; }
    Cost cost() const { return c; }
    friend std::ostream& operator<<(std::ostream& os, const edge& e) { return os << e.u << "->" << e.v << ":" << e.c; }
};
template<typename Edge>
class base_graph
{
public:
    base_graph(const usize n) : v{n}, es(n), res(n) {}
    void add_edge(const usize u, const usize v, const bool bi = false)
    {
        es[u].emplace_back(u, v), res[v].emplace_back(v, u);
        if (bi) { es[v].emplace_back(v, u), res[u].emplace_back(u, v); }
    }
    template<typename Cost>
    void add_edge(const usize u, const usize v, const Cost& c, const bool bi = false)
    {
        es[u].emplace_back(u, v, c), res[v].emplace_back(v, u, c);
        if (bi) { es[v].emplace_back(v, u, c), res[u].emplace_back(u, v, c); }
    }
    std::vector<Edge>& operator[](const usize u) { return es[u]; }
    const std::vector<Edge>& operator[](const usize u) const { return es[u]; }
    std::vector<Edge>& from(const usize u) { return es[u]; }
    const std::vector<Edge>& from(const usize u) const { return es[u]; }
    std::vector<Edge>& to(const usize v) { return res[v]; }
    const std::vector<Edge>& to(const usize v) const { return res[v]; }
    usize size() const { return v; }
    friend std::ostream& operator<<(std::ostream& os, const base_graph& g)
    {
        for (usize i = 0; i < g.v; i++) {
            for (const auto& e : g.es[i]) { os << e << '\n'; }
        }
        return os;
    }

private:
    usize v;
    std::vector<std::vector<Edge>> es, res;
};
template<typename Edge>
using base_tree = base_graph<Edge>;
using graph     = base_graph<edge<>>;
using tree      = base_graph<edge<>>;
template<typename Cost>
using cost_graph = base_graph<edge<Cost>>;
template<typename Cost>
using cost_tree = base_graph<edge<Cost>>;
int main()
{
    auto N = in<int>();
    graph g(N);
    for (int i = 0; i < N - 1; i++) {
        const auto u = in<int>() - 1, v = in<int>() - 1;
        g.add_edge(u, v, true);
    }
    const auto as = in_v<ll>({N});
    const auto bs = in_v<ll>({N});
    std::vector<ll> cs(N);
    for (int i = 0; i < N; i++) { cs[i] = bs[i] - as[i]; }
    using pll = std::pair<ll, ll>;
    std::vector<ll> push(N);    // push[i]=b     ：頂点iをした回数はx+b
    std::vector<ll> need(N);    // need[i]=b     ：頂点par[i]を押す回数はx+b
    std::vector<pll> total(N);  // total[i]=<a,b>：頂点i以下を押した回数はax+b
    SHOW(cs);
    mfp([&](auto&& self, const int s, const int p) -> void {
        ll max = 0;
        for (const int to : g[s]) {
            if (to == p) { continue; }
            self(self, to, s);
            chmax(max, need[to]);
        }
        push[s] = max;
        need[s] = cs[s] + push[s] * g[s].size();
        ll ta = 1, tb = push[s];
        for (const int to : g[s]) {
            if (to == p) { continue; }
            const ll alpha = max - need[to];
            need[s] -= push[to] + alpha;
            push[s] += push[to] + alpha;
            ta += total[to].first, tb += total[to].second + total[to].first * alpha;
        }
        total[s] = {ta, tb};
    })(0, -1);
    outln(total[0].second);
    return 0;
}
accuracy: 0.08695652173913043
time_ms: 30
memory_kb: 16664
final_rank: 20

code_snippet: #include <iostream>
#include <cmath>
#include <numeric>
#include <algorithm>
#include <deque>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <map>
#include <stack>
#include <queue>
#include <functional>
#include <climits>
#include <bitset>
#include <random>
#include <tuple>
#include <initializer_list>
#include <fstream>

struct SubTree {
	long long int min_step, back_for_minstep, need_to_push;
	long long int push_back_multiplier, sum_initial, sum_target;
};
int main() {
	int n; std::cin >> n;
	std::vector<std::vector<int>> nodes(n);
	for (auto i = 1; i < n; ++i) {
		int u, v; std::cin >> u >> v;
		nodes[--u].push_back(--v);
		nodes[v].push_back(u);
	}
	std::vector<int> initial_size(n), target_size(n);
	for (auto& a : initial_size) std::cin >> a;
	for (auto& b : target_size) std::cin >> b;
	std::vector<int> depth(n, -1), parent(n, -1), child_count(n, 0); depth[0] = 0;
	std::stack<int> stack; stack.push(0);
	while (!stack.empty()) {
		const auto top = stack.top(); stack.pop();
		for (const auto next : nodes[top]) if (depth[next] == -1) {
			depth[next] = depth[top] + 1;
			parent[next] = top;
			stack.push(next);
			++child_count[top];
		}
	}
	std::vector<SubTree> sub_trees(n);
	for (auto i = 0; i < n; ++i) if (child_count[i] == 0) {
		stack.push(i);
	}
	while (!stack.empty()) {
		const auto top = stack.top(); stack.pop();
		long long int sum_min_step{ 0 }, sum_back{ 0 }, sum_multiplier{ 0 }, max_need{ 0 }, sum_need{ 0 }, sum_initial_size{ initial_size[top] }, sum_target_size{ target_size[top] };
		for (const auto next: nodes[top]) if (depth[next] > depth[top]) {
			sum_min_step += sub_trees[next].min_step;
			sum_back += sub_trees[next].back_for_minstep;
			sum_multiplier += sub_trees[next].push_back_multiplier;
			max_need = std::max(max_need, sub_trees[next].need_to_push);
			sum_need += sub_trees[next].need_to_push;
			sum_initial_size += sub_trees[next].sum_initial;
			sum_target_size += sub_trees[next].sum_target;
		}
		const auto need_to_push{ std::max(max_need, sum_initial_size - sum_target_size) };
		sum_min_step += need_to_push;
		for (const auto next : nodes[top]) if (depth[next] > depth[top]) {
			sum_min_step += (need_to_push - sub_trees[next].need_to_push) * sub_trees[next].push_back_multiplier;
		}
		sub_trees[top] = SubTree{ sum_min_step, need_to_push, std::max(sum_target_size - sum_initial_size + need_to_push, 0LL),
			sum_multiplier + 1, sum_initial_size, sum_target_size };
		if (parent[top] != -1 && --child_count[parent[top]] == 0) {
			stack.push(parent[top]);
		}
	}
	std::cout << sub_trees[0].min_step << '\n';
}
accuracy: 1
time_ms: 100
memory_kb: 15744
final_rank: 6

code_snippet: #include <bits/stdc++.h>
using namespace std;
using i64 = long long;
#define rep(i,s,e) for(i64 (i) = (s);(i) < (e);(i)++)
#define all(x) x.begin(),x.end()

template<class T>
static inline std::vector<T> ndvec(size_t&& n, T val) noexcept {
  return std::vector<T>(n, std::forward<T>(val));
}

template<class... Tail>
static inline auto ndvec(size_t&& n, Tail&&... tail) noexcept {
  return std::vector<decltype(ndvec(std::forward<Tail>(tail)...))>(n, ndvec(std::forward<Tail>(tail)...));
}

template<class T, class Cond>
struct chain {
  Cond cond; chain(Cond cond) : cond(cond) {}
  bool operator()(T& a, const T& b) const {
    if(cond(a, b)) { a = b; return true; }
    return false;
  }
};
template<class T, class Cond>
chain<T, Cond> make_chain(Cond cond) { return chain<T, Cond>(cond); }

i64 N;
vector<vector<i64>> G;

vector<i64> A, B;
vector<i64> D;

void dfs(i64 v, i64 f) {
  for(auto t: G[v]) {
    if(t == f) continue;
    dfs(t, v);
    D[v] += D[t];
  }
}

vector<i64> X;

void dfs2(i64 v, i64 f) {
  for(auto t: G[v]) {
    if(t == f) continue;
    X[t] = X[v] - D[t];
    dfs2(t, v);
  }
}

int main() {
  cin >> N;
  G.resize(N);
  rep(i,0,N - 1) {
    i64 a, b;
    cin >> a >> b;
    a--;
    b--;
    G[a].push_back(b);
    G[b].push_back(a);
  }

  A.resize(N);
  B.resize(N);
  D.resize(N);
  rep(i,0,N) {
    cin >> A[i];
  }
  rep(i,0,N) {
    cin >> B[i];
  }
  rep(i,0,N) {
    D[i] = B[i] - A[i];
  }

  dfs(0, -1);
  X.resize(N);
  dfs2(0, -1);

  i64 MIN = *min_element(all(X));
  i64 ans = 0;
  rep(i,0,N) {
    ans += X[i] - MIN;
  }
  cout << ans << endl;
}
accuracy: 1
time_ms: 100
memory_kb: 17304
final_rank: 8