Problem:
F: 宝探し
問題
\(N\) 個の島と \(N-1\) 個の橋があります。島には 島 \(1\), 島 \(2\), …, 島 \(N\) と番号がついています。
橋 \(i\) は島 \(u_i\) と \(v_i\) をつないでおり、双方向に行き来可能です。
島 \(i\) には \(a_i\) 人の発掘隊員がいて、重さ \(b_i\) の宝があります。
あなたは発掘隊に①か②の命令を任意の順序で何回でも出すことができます。命令を出したあと発掘隊員たちは即座に行動を終えます。同時に \(2\) つ以上の命令を出すことはできません。
①島 \(i\) にいる発掘隊員の数 \(d_i\) が宝の重さ \(b_i\) 以上である島 \(i\) を選んで島 \(i\) にいる発掘隊全員に宝を発掘させる。
②島 \(i\) を選んで島 \(i\) にいる発掘隊員 \(d_i\) 人のうち \(x(x\le d_i)\) 人を島 \(i\) と直接橋でつながっている島 \(j\) に移動させる。\(x\) 人全員が移動を終えると島 \(i\) と島 \(j\) をつなぐ橋を爆発させ、今後の使用ができない状態にする。
発掘することができる宝の数の最大値を求めてください。
制約
\(2\le N\le 500\)
\(1\le a_i,b_i \le 500\)
\(1\le u_i,v_i \le N\)
初期状態ですべての島は連結である。
入力はすべて整数
入力
N
a_1
a_2
...
a_N
b_1
b_2
...
b_N
u_1
v_1
u_2
v_2
︙
u_{N-1}
v_{N-1}
出力
発掘することができる宝の数の最大値を出力してください。
入力例1
3
5 5 1
6 2 7
3 1
1 2
出力例1
3
以下のようにすると \(3\) つの宝を発掘することができます。
島 \(2\) で宝を発掘する。
島 \(2\) にいる隊員のうち \(3\) 人を島 \(1\) に移動させる。
島 \(1\) で宝を発掘する。
島 \(1\) にいる隊員のうち \(8\) 人を島 \(3\) に移動させる。
島 \(3\) で宝を発掘する。
入力例2
2
2 7
4 6
2 1
出力例2
2

Submitted solutions:

code_snippet: #define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,m,n) for(int i=(m);i<(n);++i)
#define REP(i,n) FOR(i,0,n)
#define ALL(v) (v).begin(),(v).end()
using ll = long long;
constexpr int INF = 0x3f3f3f3f;
constexpr long long LINF = 0x3f3f3f3f3f3f3f3fLL;
constexpr double EPS = 1e-8;
constexpr int MOD = 1000000007;
// constexpr int MOD = 998244353;
constexpr int DY4[]{1, 0, -1, 0}, DX4[]{0, -1, 0, 1};
constexpr int DY8[]{1, 1, 0, -1, -1, -1, 0, 1};
constexpr int DX8[]{0, -1, -1, -1, 0, 1, 1, 1};
template <typename T, typename U>
inline bool chmax(T& a, U b) { return a < b ? (a = b, true) : false; }
template <typename T, typename U>
inline bool chmin(T& a, U b) { return a > b ? (a = b, true) : false; }
struct IOSetup {
  IOSetup() {
    std::cin.tie(nullptr);
    std::ios_base::sync_with_stdio(false);
    std::cout << fixed << setprecision(20);
  }
} iosetup;

// https://hackmd.io/@olphe/HkwpLVNG9
// https://twitter.com/_olphe/status/1505452763987456001
int main() {
  constexpr int M = 500;
  int n; cin >> n;
  vector<int> a(n), b(n);
  REP(i, n) cin >> a[i];
  REP(i, n) cin >> b[i];
  vector<vector<int>> graph(n);
  REP(_, n - 1) {
    int u, v; cin >> u >> v; --u; --v;
    graph[u].emplace_back(v);
    graph[v].emplace_back(u);
  }
  auto f = [&](auto&& f, int par, int ver) -> vector<int> {
    vector dp(1, vector(M + 1, -INF));
    dp[0][0] = 0;
    for (int e : graph[ver]) {
      if (e == par) continue;
      const vector<int> child = f(f, ver, e);
      const int x = dp.size() - 1, y = child.size() - 1;
      vector nxt(x + y + 1, vector(M + 1, -INF));
      REP(i, x + 1) REP(j, y + 1) REP(k, M + 1) {
        chmax(nxt[i + j][min(k + max(child[j], 0), M)], dp[i][k] + child[j]);
      }
      dp.swap(nxt);
    }
    const int x = dp.size();
    vector<int> res(x + 1, -INF);
    REP(i, x) {
      chmax(res[i], *max_element(ALL(dp[i])) + a[ver]);
      REP(j, M + 1) {
        if (a[ver] + j >= b[ver]) {
          chmax(res[i + 1], dp[i][j] + a[ver]);
        } else {
          chmax(res[i + 1], min(a[ver] + j - b[ver], dp[i][j] + a[ver]));
        }
      }
    }
    // cerr << ver + 1 << ": ";
    // REP(i, x + 1) cerr << res[i] << " \n"[i == x];
    return res;
  };
  const vector<int> dp = f(f, -1, 0);
  for (int ans = n; ans >= 0; --ans) {
    if (dp[ans] >= 0) {
      cout << ans << '\n';
      return 0;
    }
  }
  assert(false);
}
accuracy: 1
time_ms: 120
memory_kb: 5276
final_rank: 3

code_snippet: #include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <chrono>
#include <cmath>
#include <complex>
#include <deque>
#include <forward_list>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace std;
using lint = long long;
using pint = pair<int, int>;
using plint = pair<lint, lint>;
struct fast_ios { fast_ios(){ cin.tie(nullptr), ios::sync_with_stdio(false), cout << fixed << setprecision(20); }; } fast_ios_;
#define ALL(x) (x).begin(), (x).end()
#define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i<i##_end_;i++)
#define IFOR(i, begin, end) for(int i=(end)-1,i##_begin_=(begin);i>=i##_begin_;i--)
#define REP(i, n) FOR(i,0,n)
#define IREP(i, n) IFOR(i,0,n)
template <typename T, typename V>
void ndarray(vector<T>& vec, const V& val, int len) { vec.assign(len, val); }
template <typename T, typename V, typename... Args> void ndarray(vector<T>& vec, const V& val, int len, Args... args) { vec.resize(len), for_each(begin(vec), end(vec), [&](T& v) { ndarray(v, val, args...); }); }
template <typename T> bool chmax(T &m, const T q) { return m < q ? (m = q, true) : false; }
template <typename T> bool chmin(T &m, const T q) { return m > q ? (m = q, true) : false; }
int floor_lg(long long x) { return x <= 0 ? -1 : 63 - __builtin_clzll(x); }
template <typename T1, typename T2> pair<T1, T2> operator+(const pair<T1, T2> &l, const pair<T1, T2> &r) { return make_pair(l.first + r.first, l.second + r.second); }
template <typename T1, typename T2> pair<T1, T2> operator-(const pair<T1, T2> &l, const pair<T1, T2> &r) { return make_pair(l.first - r.first, l.second - r.second); }
template <typename T> vector<T> sort_unique(vector<T> vec) { sort(vec.begin(), vec.end()), vec.erase(unique(vec.begin(), vec.end()), vec.end()); return vec; }
template <typename T> int arglb(const std::vector<T> &v, const T &x) { return std::distance(v.begin(), std::lower_bound(v.begin(), v.end(), x)); }
template <typename T> int argub(const std::vector<T> &v, const T &x) { return std::distance(v.begin(), std::upper_bound(v.begin(), v.end(), x)); }
template <typename T> istream &operator>>(istream &is, vector<T> &vec) { for (auto &v : vec) is >> v; return is; }
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) { os << '['; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <typename T, size_t sz> ostream &operator<<(ostream &os, const array<T, sz> &arr) { os << '['; for (auto v : arr) os << v << ','; os << ']'; return os; }
#if __cplusplus >= 201703L
template <typename... T> istream &operator>>(istream &is, tuple<T...> &tpl) { std::apply([&is](auto &&... args) { ((is >> args), ...);}, tpl); return is; }
template <typename... T> ostream &operator<<(ostream &os, const tuple<T...> &tpl) { os << '('; std::apply([&os](auto &&... args) { ((os << args << ','), ...);}, tpl); return os << ')'; }
#endif
template <typename T> ostream &operator<<(ostream &os, const deque<T> &vec) { os << "deq["; for (auto v : vec) os << v << ','; os << ']'; return os; }
template <typename T> ostream &operator<<(ostream &os, const set<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T, typename TH> ostream &operator<<(ostream &os, const unordered_set<T, TH> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T> ostream &operator<<(ostream &os, const multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T> ostream &operator<<(ostream &os, const unordered_multiset<T> &vec) { os << '{'; for (auto v : vec) os << v << ','; os << '}'; return os; }
template <typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &pa) { os << '(' << pa.first << ',' << pa.second << ')'; return os; }
template <typename TK, typename TV> ostream &operator<<(ostream &os, const map<TK, TV> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
template <typename TK, typename TV, typename TH> ostream &operator<<(ostream &os, const unordered_map<TK, TV, TH> &mp) { os << '{'; for (auto v : mp) os << v.first << "=>" << v.second << ','; os << '}'; return os; }
#ifdef HITONANODE_LOCAL
const string COLOR_RESET = "\033[0m", BRIGHT_GREEN = "\033[1;32m", BRIGHT_RED = "\033[1;31m", BRIGHT_CYAN = "\033[1;36m", NORMAL_CROSSED = "\033[0;9;37m", RED_BACKGROUND = "\033[1;41m", NORMAL_FAINT = "\033[0;2m";
#define dbg(x) cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << NORMAL_FAINT << " (L" << __LINE__ << ") " << __FILE__ << COLOR_RESET << endl
#define dbgif(cond, x) ((cond) ? cerr << BRIGHT_CYAN << #x << COLOR_RESET << " = " << (x) << NORMAL_FAINT << " (L" << __LINE__ << ") " << __FILE__ << COLOR_RESET << endl : cerr)
#else
#define dbg(x) (x)
#define dbgif(cond, x) 0
#endif

int main() {
    int N;
    cin >> N;
    vector<int> A(N), B(N);
    cin >> A >> B;

    vector<vector<int>> to(N);
    REP(e, N - 1) {
        int u, v;
        cin >> u >> v;
        --u, --v;
        to[u].push_back(v);
        to[v].push_back(u);
    }
    dbg(to);

    vector<tuple<int, int, int>> subtrees; // (size, root, par[root])
    map<pint, int> mp_stsz;

    auto rec = [&](auto &&self, int now, int prv) -> int {
        int stsz = 1;
        for (auto nxt : to[now]) {
            if (nxt == prv) continue;
            stsz += self(self, nxt, now);
        }
        pint st(now, prv);
        subtrees.emplace_back(stsz, now, prv);
        mp_stsz[st] = stsz;

        // if (prv >= 0) {
        //     pint st(prv, now);
        //     subtrees.emplace_back(N - stsz, prv, now);
        //     mp_stsz[st] = N - stsz;
        // }
        return stsz;
    };

    rec(rec, 0, -1);
    // FOR(i, 1, N) subtrees.emplace_back(N, i, -1);

    subtrees = sort_unique(subtrees);

    map<pint, vector<int>> memo;

    int ret = 0;
    constexpr int INF = 1 << 22;
    for (auto [st_sz_, root, parroot] : subtrees) {
        const int b = max(B.at(root) - A.at(root), 0);

        vector dp(1, vector<int>(b + 1, INF));
        dp[0][0] = -A[root];

        for (auto nxt : to[root]) {
            if (nxt == parroot) continue;

            const auto dpnxt = memo.at(make_pair(nxt, root));

            auto dpn = dp;
            dpn.resize(dp.size() + dpnxt.size() - 1, vector<int>(b + 1, INF));

            REP(n, dp.size()) {
                REP(m, dpnxt.size()) {
                    if (n + m >= int(dpn.size())) continue;
                    auto vv = (dpnxt[m] < 0) * (-dpnxt[m]);
                    REP(k, dp[n].size()) {
                        if (dp[n][k] == INF) continue;

                        int knxt = min(b, k + vv);
                        chmin(dpn[n + m][knxt], dp[n][k] + dpnxt[m]);
                    }
                }
            }
            dp = dpn;
        }

        vector<int> dpnxt(dp.size() + 1, INF);
        REP(n, dp.size()) {
            REP(k, dp[n].size()) {
                if (dp[n][k] == INF) continue;
                chmin(dpnxt[n], dp[n][k]);
                if (k >= b) {
                    chmin(dpnxt[n + 1], dp[n][k]);
                } else {
                    chmin(dpnxt[n + 1], max(dp[n][k], b - k));
                }
            }
        }

        memo[make_pair(root, parroot)] = dpnxt;

        if (st_sz_ == N) {
            int cur = 0;
            while (cur < int(dpnxt.size()) and dpnxt[cur] <= 0) ++cur;
            chmax(ret, cur - 1);
        }
    }
    dbg(memo);
    cout << ret << '\n';
}
accuracy: 1
time_ms: 100
memory_kb: 5956
final_rank: 2

code_snippet: #include <bits/stdc++.h>
using namespace std;
const int INF = 100000000;
int main(){
  int N;
  cin >> N;
  vector<int> a(N);
  for (int i = 0; i < N; i++){
    cin >> a[i];
  }
  vector<int> b(N);
  for (int i = 0; i < N; i++){
    cin >> b[i];
  }
  vector<vector<int>> E(N);
  for (int i = 0; i < N - 1; i++){
    int u, v;
    cin >> u >> v;
    u--;
    v--;
    E[u].push_back(v);
    E[v].push_back(u);
  }
  vector<int> p(N, -1);
  vector<vector<int>> c(N);
  queue<int> Q;
  Q.push(0);
  vector<int> bfs;
  while (!Q.empty()){
    int v = Q.front();
    Q.pop();
    bfs.push_back(v);
    for (int w : E[v]){
      if (w != p[v]){
        p[w] = v;
        c[v].push_back(w);
        Q.push(w);
      }
    }
  }
  reverse(bfs.begin(), bfs.end());
  vector<vector<int>> dp(N);
  for (int v : bfs){
    vector<vector<int>> tmp(1, vector<int>(501, -INF));
    for (int i = 0; i <= a[v]; i++){
      tmp[0][i] = a[v];
    }
    for (int w : c[v]){
      int s1 = tmp.size();
      int s2 = dp[w].size();
      vector<vector<int>> tmp2(s1 + s2 - 1, vector<int>(501, -INF));
      for (int i = 0; i < s1; i++){
        for (int j = 0; j < s2; j++){
          for (int k = 0; k <= 500; k++){
            if (tmp[i][k] != -INF && dp[w][j] != -INF){
              int i2 = i + j;
              int k2 = min(k + max(dp[w][j], 0), 500);
              tmp2[i2][k2] = max(tmp2[i2][k2], tmp[i][k] + dp[w][j]);
            }
          }
        }
      }
      swap(tmp, tmp2);
    }
    int sz = tmp.size();
    dp[v] = vector<int>(sz + 1, -INF);
    for (int i = 0; i < sz; i++){
      for (int j = 0; j <= 500; j++){
        if (tmp[i][j] != -INF){
          dp[v][i] = max(dp[v][i], tmp[i][j]);
          if (j >= b[v]){
            dp[v][i + 1] = max(dp[v][i + 1], tmp[i][j]);
          } else {
            dp[v][i + 1] = max(dp[v][i + 1], min(j - b[v], tmp[i][j]));
          }
        }
      }
    }
  }
  int ans = 0;
  for (int i = 0; i <= N; i++){
    if (dp[0][i] >= 0){
      ans = i;
    }
  }
  cout << ans << endl;
}
accuracy: 1
time_ms: 70
memory_kb: 5324
final_rank: 1

code_snippet: #define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,m,n) for(int i=(m);i<(n);++i)
#define REP(i,n) FOR(i,0,n)
#define ALL(v) (v).begin(),(v).end()
using ll = long long;
constexpr int INF = 0x3f3f3f3f;
constexpr long long LINF = 0x3f3f3f3f3f3f3f3fLL;
constexpr double EPS = 1e-8;
constexpr int MOD = 1000000007;
// constexpr int MOD = 998244353;
constexpr int DY4[]{1, 0, -1, 0}, DX4[]{0, -1, 0, 1};
constexpr int DY8[]{1, 1, 0, -1, -1, -1, 0, 1};
constexpr int DX8[]{0, -1, -1, -1, 0, 1, 1, 1};
template <typename T, typename U>
inline bool chmax(T& a, U b) { return a < b ? (a = b, true) : false; }
template <typename T, typename U>
inline bool chmin(T& a, U b) { return a > b ? (a = b, true) : false; }
struct IOSetup {
  IOSetup() {
    std::cin.tie(nullptr);
    std::ios_base::sync_with_stdio(false);
    std::cout << fixed << setprecision(20);
  }
} iosetup;

// https://hackmd.io/@olphe/HkwpLVNG9
// https://twitter.com/_olphe/status/1505452763987456001
int main() {
  constexpr int M = 500;
  int n; cin >> n;
  vector<int> a(n), b(n);
  REP(i, n) cin >> a[i];
  REP(i, n) cin >> b[i];
  vector<vector<int>> graph(n);
  REP(_, n - 1) {
    int u, v; cin >> u >> v; --u; --v;
    graph[u].emplace_back(v);
    graph[v].emplace_back(u);
  }
  auto f = [&](auto&& f, int par, int ver) -> vector<int> {
    vector dp(1, vector(M + 1, -INF));
    dp[0][0] = 0;
    for (int e : graph[ver]) {
      if (e == par) continue;
      const vector<int> child = f(f, ver, e);
      const int x = dp.size() - 1, y = child.size() - 1;
      vector nxt(x + y + 1, vector(M + 1, -INF));
      REP(i, x + 1) REP(j, y + 1) REP(k, M + 1) {
        chmax(nxt[i + j][min(k + max(child[j], 0), M)], dp[i][k] + child[j]);
      }
      dp.swap(nxt);
    }
    const int x = dp.size();
    vector<int> res(x + 1, -INF);
    REP(i, x) {
      chmax(res[i], *max_element(ALL(dp[i])) + a[ver]);
      REP(j, M + 1) {
        if (a[ver] + j >= b[ver]) {
          chmax(res[i + 1], dp[i][j] + a[ver]);
        } else {
          chmax(res[i + 1], dp[i][j] + a[ver] + j - b[ver]);
        }
      }
    }
    // cout << ver + 1 << ": ";
    // REP(i, x + 1) cout << res[i] << " \n"[i == x];
    return res;
  };
  const vector<int> dp = f(f, -1, 0);
  for (int ans = n; ans >= 0; --ans) {
    if (dp[ans] >= 0) {
      cout << ans << '\n';
      return 0;
    }
  }
  assert(false);
}
accuracy: 0.2702702702702703
time_ms: 120
memory_kb: 5072
final_rank: 11

code_snippet: #include <cassert>
#include <iostream>
#include <limits>
#include <vector>

constexpr int M = 500;

constexpr int inf = std::numeric_limits<int>::max() / 2;

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

    int n;
    std::cin >> n;

    std::vector<int> a(n), b(n);
    for (auto &e : a) std::cin >> e;
    for (auto &e : b) std::cin >> e;

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

    auto merge = [&](const std::vector<std::vector<int>> &pd, const std::vector<int> &x) {
        int siz_l = pd.size(), siz_r = x.size();
        std::vector dp(siz_l + siz_r - 1, std::vector<int>(M + 1, -inf));
        for (int i = 0; i < siz_l; ++i) for (int j = 0; j < siz_r; ++j) {
            int ni = pd[i].size();
            for (int pos = 0; pos < ni; ++pos) {
                int next_pos = std::min(M, pos + std::max(x[j], 0));
                dp[i + j][next_pos] = std::max(dp[i + j][next_pos], pd[i][pos] + x[j]);
            }
        }
        return dp;
    };

    std::vector dp(n, std::vector<int>{});

    auto dfs = [&](auto dfs, int u, int p) -> void {
        if (p >= 0 and g[u].size() == 1) {
            // leaf
            if (a[u] >= b[u]) {
                dp[u] = { a[u], a[u] };
            } else {
                dp[u] = { a[u], a[u] - b[u] };
            }
            return;
        }
        std::vector<std::vector<int>> dp2 { { 0 } };
        for (int v : g[u]) {
            if (v == p) continue;
            dfs(dfs, v, u);
            dp2 = merge(dp2, dp[v]);
        }
        int siz = dp2.size();
        dp[u].resize(siz + 1, -inf);
        for (int i = 0; i < siz; ++i) for (int j = 0; j <= M; ++j) {
            if (a[u] + j >= b[u]) {
                dp[u][i + 1] = std::max(dp[u][i + 1], dp2[i][j] + a[u]);
            } else {
                dp[u][i] = std::max(dp[u][i], dp2[i][j] + a[u]);
                dp[u][i + 1] = std::max(dp[u][i + 1], std::min(-b[u], dp2[i][j] + a[u]));
            }
        }
    };
    dfs(dfs, 0, -1);

    int siz = dp[0].size();
    for (int i = siz - 1; i >= 0; --i) {
        if (dp[0][i] >= 0) {
            std::cout << i << std::endl;
            return 0;
        }
    }

    assert(false);

    return 0;
}
accuracy: 1
time_ms: 130
memory_kb: 5252
final_rank: 4

code_snippet: #include <bits/stdc++.h>

using namespace std;

using int64 = long long;
//const int mod = 1e9 + 7;
const int mod = 998244353;

const int64 infll = (1LL << 62) - 1;
const int inf = (1 << 30) - 1;

struct IoSetup {
  IoSetup() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(10);
    cerr << fixed << setprecision(10);
  }
} iosetup;


template< typename T1, typename T2 >
ostream &operator<<(ostream &os, const pair< T1, T2 > &p) {
  os << p.first << " " << p.second;
  return os;
}

template< typename T1, typename T2 >
istream &operator>>(istream &is, pair< T1, T2 > &p) {
  is >> p.first >> p.second;
  return is;
}

template< typename T >
ostream &operator<<(ostream &os, const vector< T > &v) {
  for(int i = 0; i < (int) v.size(); i++) {
    os << v[i] << (i + 1 != v.size() ? " " : "");
  }
  return os;
}

template< typename T >
istream &operator>>(istream &is, vector< T > &v) {
  for(T &in: v) is >> in;
  return is;
}

template< typename T1, typename T2 >
inline bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); }

template< typename T1, typename T2 >
inline bool chmin(T1 &a, T2 b) { return a > b && (a = b, true); }

template< typename T = int64 >
vector< T > make_v(size_t a) {
  return vector< T >(a);
}

template< typename T, typename... Ts >
auto make_v(size_t a, Ts... ts) {
  return vector< decltype(make_v< T >(ts...)) >(a, make_v< T >(ts...));
}

template< typename T, typename V >
typename enable_if< is_class< T >::value == 0 >::type fill_v(T &t, const V &v) {
  t = v;
}

template< typename T, typename V >
typename enable_if< is_class< T >::value != 0 >::type fill_v(T &t, const V &v) {
  for(auto &e: t) fill_v(e, v);
}

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)};
}

int main() {
  int N;
  cin >> N;
  vector< int > A(N), B(N);
  cin >> A >> B;
  vector< vector< int > > g(N);
  for(int i = 1; i < N; i++) {
    int a, b;
    cin >> a >> b;
    --a, --b;
    g[a].emplace_back(b);
    g[b].emplace_back(a);
  }
  const int M = 500;
  using vi = vector< int >;
  auto rec = MFP([&](auto rec, int idx, int par) -> vi {
    auto upL = make_v< int >(1, M + 1);
    fill_v(upL, -inf);
    upL[0][A[idx]] = A[idx];
    for(auto to: g[idx]) {
      if(to == par) continue;
      auto sup = rec(to, idx);
      auto upR = make_v< int >(upL.size() + sup.size() - 1, M + 1);
      fill_v(upR, -inf);
      for(int i = 0; i < upL.size(); i++) {
        for(int k = 0; k < sup.size(); k++) {
          for(int j = 0; j <= M; j++) {
            chmax(upR[i + k][min(M, max(j, j + sup[k]))], upL[i][j] + sup[k]);
          }
        }
      }
      upL = upR;
    }
    vector< int > uku(upL.size() + 1, -inf);
    for(int i = 0; i < upL.size(); i++) {
      for(int j = 0; j < B[idx]; j++) chmax(uku[i], upL[i][j]);
      for(int j = 0; j < B[idx]; j++) chmax(uku[i + 1], min(j - B[idx], upL[i][j]));
      for(int j = B[idx]; j <= M; j++) chmax(uku[i + 1], upL[i][j]);
    }
    return uku;
  });
  auto ret = rec(0, -1);
  for(int i = (int) ret.size() - 1; i >= 0; i--) {
    if(ret[i] >= 0) {
      cout << i << "\n";
      return 0;
    }
  }
}
accuracy: 1
time_ms: 210
memory_kb: 6148
final_rank: 6

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef unsigned long long int ull;
typedef long long int ll;
typedef pair<ll,ll> pll;
typedef long double D;
//typedef complex<D> P;
#define F first
#define S second
//const ll MOD=1000000007;
const ll MOD=998244353;

template<typename T,typename U>istream & operator >> (istream &i,pair<T,U> &A){i>>A.F>>A.S; return i;}
template<typename T>istream & operator >> (istream &i,vector<T> &A){for(auto &I:A){i>>I;} return i;}
template<typename T,typename U>ostream & operator << (ostream &o,const pair<T,U> &A){o<<A.F<<" "<<A.S; return o;}
template<typename T>ostream & operator << (ostream &o,const vector<T> &A){int i=A.size(); for(auto &I:A){o<<I<<(--i?" ":"");} return o;}
template<typename T,typename U>T & chmax(T &a,const U &b){if(a<b){a=b;} return a;}
template<typename T,typename U>T & chmin(T &a,const U &b){if(b<a){a=b;} return a;}

const int INF=1e8;

int N;
vector<int> A,B;
vector<vector<int>> edge;
vector<vector<int>> dp;
vector<vector<vector<int>>> UKU(505,vector<vector<int>>(505,vector<int>(505)));


void merge(int u,int v,int n,int M){
  auto &uku=UKU[u];
  int m=dp[v].size();
  for(int i=n;i+1<n+m;i++){
    for(int k=0;k<M;k++){
      uku[i][k]=-INF;
    }
  }
  
  for(int i=n-1;i>=0;i--){
    for(int j=m-1;j>=0;j--){
      for(int k=M-1;k>=0;k--){
	int tmp=uku[i][k]+dp[v][j];
        chmax(uku[i+j][min(k+max(dp[v][j],0),M-1)],tmp);
      }
    }
  }
}

void dfs(int u,int p){
  int M=B[u]+1;
  int n=1;
  for(int i=0;i<n;i++){
    for(int j=0;j<M;j++){UKU[u][i][j]=-INF;}
  }
  UKU[u][0][min(A[u],B[u])]=0;
  
  for(auto &v:edge[u]){
    if(v==p){continue;}
    dfs(v,u);
    merge(u,v,n,M);
    n+=dp[v].size()-1;
  }
  dp[u].resize(n+1,-INF);
  for(int i=0;i<n;i++){
    for(int j=0;j<M;j++){
      chmax(dp[u][i],UKU[u][i][j]+A[u]);
      if(j>=B[u]){chmax(dp[u][i+1],UKU[u][i][j]+A[u]);}
      else if(UKU[u][i][j]>=-INF/3){chmax(dp[u][i+1],min(j-B[u],UKU[u][i][j]+A[u]));}
    }
  }
}


int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  
  cin>>N;
  A.resize(N);
  B.resize(N);
  edge.resize(N);
  dp.resize(N);
  cin>>A>>B;
  for(int i=1;i<N;i++){
    int u,v;
    cin>>u>>v;
    u--; v--;
    edge[u].push_back(v);
    edge[v].push_back(u);
  }
  dfs(0,-1);
  ll ans=-1;
  for(int i=0;i<=N;i++){
    if(dp[0][i]>=0){ans=i;}
  }
  assert(ans!=-1);
  cout<<ans<<endl;

  return 0;
}
accuracy: 1
time_ms: 260
memory_kb: 515940
final_rank: 10

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef unsigned long long int ull;
typedef long long int ll;
typedef pair<ll,ll> pll;
typedef long double D;
//typedef complex<D> P;
#define F first
#define S second
//const ll MOD=1000000007;
const ll MOD=998244353;

template<typename T,typename U>istream & operator >> (istream &i,pair<T,U> &A){i>>A.F>>A.S; return i;}
template<typename T>istream & operator >> (istream &i,vector<T> &A){for(auto &I:A){i>>I;} return i;}
template<typename T,typename U>ostream & operator << (ostream &o,const pair<T,U> &A){o<<A.F<<" "<<A.S; return o;}
template<typename T>ostream & operator << (ostream &o,const vector<T> &A){int i=A.size(); for(auto &I:A){o<<I<<(--i?" ":"");} return o;}
template<typename T,typename U>T & chmax(T &a,const U &b){if(a<b){a=b;} return a;}
template<typename T,typename U>T & chmin(T &a,const U &b){if(b<a){a=b;} return a;}

const int INF=1e7;

int N;
vector<int> A,B;
vector<vector<int>> edge;
vector<vector<int>> dp;
vector<vector<vector<int>>> UKU(505,vector<vector<int>>(505,vector<int>(505)));


void merge(int u,int v,int n,int M){
  auto &uku=UKU[u];
  int m=dp[v].size();
  for(int i=n;i+1<n+m;i++){
    for(int k=0;k<M;k++){
      uku[i][k]=-INF;
    }
  }
  
  for(int i=n-1;i>=0;i--){
    for(int j=m-1;j>=0;j--){
      for(int k=M-1;k>=0;k--){
	int tmp=uku[i][k]+dp[v][j];
        chmax(uku[i+j][min(k+max(dp[v][j],0),M-1)],tmp);
      }
    }
  }
}

void dfs(int u,int p){
  int M=B[u]+1;
  int n=1;
  for(int i=0;i<n;i++){
    for(int j=0;j<M;j++){UKU[u][i][j]=-INF;}
  }
  UKU[u][0][min(A[u],B[u])]=0;
  
  for(auto &v:edge[u]){
    if(v==p){continue;}
    dfs(v,u);
    merge(u,v,n,M);
    n+=dp[v].size()-1;
  }
  dp[u].resize(n+1,-INF);
  for(int i=0;i<n;i++){
    for(int j=0;j<M;j++){
      chmax(dp[u][i],UKU[u][i][j]+A[u]);
      if(j>=B[u]){chmax(dp[u][i+1],UKU[u][i][j]+A[u]);}
      else if(UKU[u][i][j]>=-INF/3){chmax(dp[u][i+1],j-B[u]);}
    }
  }
}


int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  
  cin>>N;
  A.resize(N);
  B.resize(N);
  edge.resize(N);
  dp.resize(N);
  cin>>A>>B;
  for(int i=1;i<N;i++){
    int u,v;
    cin>>u>>v;
    u--; v--;
    edge[u].push_back(v);
    edge[v].push_back(u);
  }
  dfs(0,-1);
  ll ans=-1;
  for(int i=0;i<=N;i++){
    if(dp[0][i]>=0){ans=i;}
  }
  assert(ans!=-1);
  cout<<ans<<endl;

  return 0;
}
accuracy: 0.10810810810810811
time_ms: 160
memory_kb: 515872
final_rank: 14

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef unsigned long long int ull;
typedef long long int ll;
typedef pair<ll,ll> pll;
typedef long double D;
//typedef complex<D> P;
#define F first
#define S second
//const ll MOD=1000000007;
const ll MOD=998244353;

template<typename T,typename U>istream & operator >> (istream &i,pair<T,U> &A){i>>A.F>>A.S; return i;}
template<typename T>istream & operator >> (istream &i,vector<T> &A){for(auto &I:A){i>>I;} return i;}
template<typename T,typename U>ostream & operator << (ostream &o,const pair<T,U> &A){o<<A.F<<" "<<A.S; return o;}
template<typename T>ostream & operator << (ostream &o,const vector<T> &A){int i=A.size(); for(auto &I:A){o<<I<<(--i?" ":"");} return o;}
template<typename T,typename U>T & chmax(T &a,const U &b){if(a<b){a=b;} return a;}
template<typename T,typename U>T & chmin(T &a,const U &b){if(b<a){a=b;} return a;}

const int INF=1e7;

int N;
vector<int> A,B;
vector<vector<int>> edge;
vector<vector<int>> dp;
vector<vector<vector<int>>> UKU(505,vector<vector<int>>(505,vector<int>(505)));


void merge(int u,int v,int n,int M){
  auto &uku=UKU[u];
  int m=dp[v].size();
  for(int i=n;i+1<n+m;i++){
    for(int k=0;k<M;k++){
      uku[i][k]=-INF;
    }
  }
  
  for(int i=n-1;i>=0;i--){
    for(int j=m-1;j>=0;j--){
      for(int k=M-1;k>=0;k--){
	int tmp=uku[i][k]+dp[v][j];
        chmax(uku[i+j][min(k+max(dp[v][j],0),M-1)],tmp);
      }
    }
  }
}

void dfs(int u,int p){
  int M=B[u]+1;
  int n=1;
  for(int i=0;i<n;i++){
    for(int j=0;j<M;j++){UKU[u][i][j]=-INF;}
  }
  UKU[u][0][min(A[u],B[u])]=0;
  
  for(auto &v:edge[u]){
    if(v==p){continue;}
    dfs(v,u);
    merge(u,v,n,M);
    n+=dp[v].size()-1;
  }
  dp[u].resize(n+1,-INF);
  for(int i=0;i<n;i++){
    for(int j=0;j<M;j++){
      chmax(dp[u][i],UKU[u][i][j]+A[u]);
      if(j>=B[u]){chmax(dp[u][i+1],UKU[u][i][j]+A[u]);}
      else if(UKU[u][i][j]>=-INF/3){chmax(dp[u][i+1],j-B[u]);}
    }
  }
}


int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  
  cin>>N;
  A.resize(N);
  B.resize(N);
  edge.resize(N);
  dp.resize(N);
  cin>>A>>B;
  for(int i=1;i<N;i++){
    int u,v;
    cin>>u>>v;
    u--; v--;
    edge[u].push_back(v);
    edge[v].push_back(u);
  }
  dfs(0,-1);
  ll ans=-1;
  for(int i=0;i<=N;i++){
    if(dp[0][i]>=0){ans=i;}
  }
  cout<<ans<<endl;

  return 0;
}
accuracy: 0.10810810810810811
time_ms: 160
memory_kb: 515820
final_rank: 13

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef unsigned long long int ull;
typedef long long int ll;
typedef pair<ll,ll> pll;
typedef long double D;
//typedef complex<D> P;
#define F first
#define S second
//const ll MOD=1000000007;
const ll MOD=998244353;

template<typename T,typename U>istream & operator >> (istream &i,pair<T,U> &A){i>>A.F>>A.S; return i;}
template<typename T>istream & operator >> (istream &i,vector<T> &A){for(auto &I:A){i>>I;} return i;}
template<typename T,typename U>ostream & operator << (ostream &o,const pair<T,U> &A){o<<A.F<<" "<<A.S; return o;}
template<typename T>ostream & operator << (ostream &o,const vector<T> &A){int i=A.size(); for(auto &I:A){o<<I<<(--i?" ":"");} return o;}
template<typename T,typename U>T & chmax(T &a,const U &b){if(a<b){a=b;} return a;}
template<typename T,typename U>T & chmin(T &a,const U &b){if(b<a){a=b;} return a;}

const int INF=1e7;

int N;
vector<int> A,B;
vector<vector<int>> edge;
vector<vector<int>> dp;
vector<vector<vector<int>>> UKU(505,vector<vector<int>>(505,vector<int>(505)));


void merge(int u,int v,int n,int M){
  auto &uku=UKU[u];
  int m=dp[v].size();
  for(int i=n;i+1<n+m;i++){
    for(int k=0;k<M;k++){
      uku[i][k]=-INF;
    }
  }
  
  for(int i=n-1;i>=0;i--){
    for(int j=m-1;j>=0;j--){
      for(int k=M-1;k>=0;k--){
        chmax(uku[i+j][min(k+max(dp[v][j],0),M-1)],uku[i][k]+dp[v][j]);
      }
    }
  }
}

void dfs(int u,int p){
  int M=B[u]+1;
  int n=1;
  for(int i=0;i<n;i++){
    for(int j=0;j<M;j++){UKU[u][i][j]=-INF;}
  }
  UKU[u][0][min(A[u],B[u])]=0;
  
  for(auto &v:edge[u]){
    if(v==p){continue;}
    dfs(v,u);
    merge(u,v,n,M);
    n+=dp[v].size()-1;
  }
  dp[u].resize(n+1,-INF);
  for(int i=0;i<n;i++){
    for(int j=0;j<M;j++){
      chmax(dp[u][i],UKU[u][i][j]+A[u]);
      if(j>=B[u]){chmax(dp[u][i+1],UKU[u][i][j]+A[u]);}
      else if(UKU[u][i][j]>=-INF/3){chmax(dp[u][i+1],j-B[u]);}
    }
  }
}


int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  
  cin>>N;
  A.resize(N);
  B.resize(N);
  edge.resize(N);
  dp.resize(N);
  cin>>A>>B;
  for(int i=1;i<N;i++){
    int u,v;
    cin>>u>>v;
    u--; v--;
    edge[u].push_back(v);
    edge[v].push_back(u);
  }
  dfs(0,-1);
  ll ans=-1;
  for(int i=0;i<=N;i++){
    if(dp[0][i]>=0){ans=i;}
  }
  cout<<ans<<endl;

  return 0;
}
accuracy: 0.10810810810810811
time_ms: 160
memory_kb: 515792
final_rank: 12

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
#define inf 500000007
#define MP make_pair
#define MT make_tuple
#define PB push_back
#define fi first
#define se second
#define rep(i,n) for(int i = 0; i < (int)(n); ++i)
#define rrep(i,n) for(int i = (int)n-1; i >= 0; --i)
#define srep(i,a,b) for(int i = (int)a; i < (int)(b); ++i)
#define all(x) (x).begin(),(x).end()
#define SUM(v) accumulate(all(v), 0LL)
#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#define lb(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define ub(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define UNIQUE(x) sort(all(x)), x.erase(unique(all(x)), x.end())
#define SZ(c) (int)(c).size()
template<typename T>
ostream& operator << (ostream& os, vector<T>& vec) {
    os << "{";
    for (int i = 0; i<(int)vec.size(); i++) {
        os << vec[i] << (i + 1 == (int)vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
// pair出力
template<typename T, typename U>
ostream& operator << (ostream& os, pair<T, U> pair_var) {
    os << "(" << pair_var.first << ", " << pair_var.second << ")";
    return os;
}
// map出力
template<typename T, typename U>
ostream& operator << (ostream& os, map<T, U>& map_var) {
    os << "{";
    for(auto itr = map_var.begin(); itr != map_var.end(); itr++){
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if(itr != map_var.end()) os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
// set 出力
template<typename T>
ostream& operator << (ostream& os, set<T>& set_var) {
    os << "{";
    for(auto itr = set_var.begin(); itr != set_var.end(); itr++){
        os << (*itr);
        ++itr;
        if(itr != set_var.end()) os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
// tuple 出力
template<int N,class Tuple>
void out(ostream &os,const Tuple &t){}
template<int N,class Tuple,class H,class ...Ts>
void out(ostream &os,const Tuple &t){
    if(N)os<<", ";
    os<<get<N>(t);
    out<N+1,Tuple,Ts...>(os,t);
}
template<class ...Ts>
ostream& operator<<(ostream &os, const tuple<Ts...> &t){
    os<<"(";
    out<0,tuple<Ts...>,Ts...>(os,t);
    os<<")";
    return os;
}
#define overload2(_1, _2, name, ...) name
#define vec(type, name, ...) vector<type> name(__VA_ARGS__)
#define VEC(type, name, size)                                                                                                                                  \
    vector<type> name(size);                                                                                                                                   \
    IN(name)
#define vv(type, name, h, ...) vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define VV(type, name, h, w)                                                                                                                                   \
    vector<vector<type>> name(h, vector<type>(w));                                                                                                             \
    IN(name)
#define vvv(type, name, h, w, ...) vector<vector<vector<type>>> name(h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...)                                                                                                                         \
    vector<vector<vector<vector<type>>>> name(a, vector<vector<vector<type>>>(b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))
#define INT(...)                                                                                                                                               \
    int __VA_ARGS__;                                                                                                                                           \
    IN(__VA_ARGS__)
#define LL(...)                                                                                                                                                \
    ll __VA_ARGS__;                                                                                                                                            \
    IN(__VA_ARGS__)
#define STR(...)                                                                                                                                               \
    string __VA_ARGS__;                                                                                                                                        \
    IN(__VA_ARGS__)
#define CHR(...)                                                                                                                                               \
    char __VA_ARGS__;                                                                                                                                          \
    IN(__VA_ARGS__)
#define DBL(...)                                                                                                                                               \
    double __VA_ARGS__;                                                                                                                                        \
    IN(__VA_ARGS__)
int scan() { return getchar(); }
void scan(int &a) { cin >> a; }
void scan(long long &a) { cin >> a; }
void scan(char &a) { cin >> a; }
void scan(double &a) { cin >> a; }
void scan(string &a) { cin >> a; }
template <class T, class S> void scan(pair<T, S> &p) { scan(p.first), scan(p.second); }
template <class T> void scan(vector<T> &);
template <class T> void scan(vector<T> &a) {
    for(auto &i : a) scan(i);
}
template <class T> void scan(T &a) { cin >> a; }
void IN() {}
template <class Head, class... Tail> void IN(Head &head, Tail &...tail) {
    scan(head);
    IN(tail...);
}
const string YESNO[2] = {"NO", "YES"};
const string YesNo[2] = {"No", "Yes"};
const string yesno[2] = {"no", "yes"};
void YES(bool t = 1) { cout << YESNO[t] << endl; }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { cout << YesNo[t] << endl; }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { cout << yesno[t] << endl; }
void no(bool t = 1) { yes(!t); }
#ifdef LOCAL
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
    cerr << " " << H;
    debug_out(T...);
}
#define dbg(...) \
    cerr << __LINE__ << " [" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#define dump(x) cerr << __LINE__ << " " << #x << " = " << (x) << endl
#else
#define dbg(...) (void(0))
#define dump(x) (void(0))
#endif
template<typename A, typename T>
std::enable_if_t<std::is_convertible<T, A>::value> fill(A& array, const T& val)
{
    array = val;
}
template<typename A, typename T>
std::enable_if_t<!std::is_convertible<T, A>::value> fill(A& array, const T& val)
{
    for (auto& a : array) {
        fill(a, val);
    }
}
template <typename T, typename S> T ceil(T x, S y) {
    assert(y);
    return (y < 0 ? ceil(-x, -y) : (x > 0 ? (x + y - 1) / y : x / y));
}
template <typename T, typename S> T floor(T x, S y) {
    assert(y);
    return (y < 0 ? floor(-x, -y) : (x > 0 ? x / y : x / y - (x % y == 0 ? 0 : 1)));
}
vector<int> iota(int n) {vector<int> a(n);iota(all(a), 0);return a;}
template <class T> T POW(T x, int n) {T res = 1;for(; n; n >>= 1, x *= x){if(n & 1) res *= x;}return res;}
ll pow2(int i) { return 1LL << i; }
int topbit(signed t) { return t == 0 ? -1 : 31 - __builtin_clz(t); }
int topbit(ll t) { return t == 0 ? -1 : 63 - __builtin_clzll(t); }
int lowbit(signed a) { return a == 0 ? 32 : __builtin_ctz(a); }
int lowbit(ll a) { return a == 0 ? 64 : __builtin_ctzll(a); }
// int allbit(int n) { return (1 << n) - 1; }
ll allbit(ll n) { return (1LL << n) - 1; }
int popcount(signed t) { return __builtin_popcount(t); }
int popcount(ll t) { return __builtin_popcountll(t); }
bool ispow2(int i) { return i && (i & -i) == i; }


template <class S> void fold_in(vector<S> &v) {}
template <typename Head, typename... Tail, class S> void fold_in(vector<S> &v, Head &&a, Tail &&...tail) {
    for(auto e : a) v.emplace_back(e);
    fold_in(v, tail...);
}
template <class S> void renumber(vector<S> &v) {}
template <typename Head, typename... Tail, class S> void renumber(vector<S> &v, Head &&a, Tail &&...tail) {
    for(auto &&e : a) e = lb(v, e);
    renumber(v, tail...);
}
template <class S, class... Args> void zip(vector<S> &head, Args &&...args) {
    vector<S> v;
    fold_in(v, head, args...);
    sort(all(v)), v.erase(unique(all(v)), v.end());
    renumber(v, head, args...);
}
template<class T> inline bool chmax(T &a, T b){
    if(a<b){
        a = b;
        return true;
    }
    return false;
}
template<class T> inline bool chmin(T &a, T b){
    if(a>b){
        a = b;
        return true;
    }
    return false;
}

int main(){
    INT(n);
    VEC(int,a,n);
    VEC(int,b,n);
    vv(int,G,n);
    rep(i,n-1){
        INT(u,v);
        u--;v--;
        G[u].push_back(v);
        G[v].push_back(u);
    }
    int M =500;
    vector<vector<int> > dp(n);
    vector<int> sub(n);
    auto dfs = [&](auto&&F,int id,int pre)->void{
        dbg(id);
        vv(int,f,M+1,1,-inf);
        f[a[id]][0] = a[id];
        sub[id]++;
        for(auto x:G[id]){
            if(x==pre)continue;
            F(F,x,id);
            sub[id] += sub[x];
            auto &g = dp[x];
            int sf = f[0].size();
            int sg = g.size();
            vv(int,h,M+1,sf+sg-1,-inf);
            rep(i,sf){
                rep(j,sg){
                    // i + j ;
                    for(int k=0;k<=M;k++){
                        if(g[j]>=0){
                            int C = k + g[j];
                            if(k+g[j]>=M){
                                C = M;
                            }
                            chmax(h[C][i+j],f[k][i] + g[j]); 

                        }else{
                            chmax(h[k][i+j],f[k][i] + g[j]); 
                        }
                    }
                }
            }
            dbg(f);
            dbg(g);
            dbg(h);
            swap(f,h);
        }
        dbg(id);
        dbg(f);
        vector<int> res(sub[id]+1,-inf);
        for(int k=0;k<=M;k++){
            for(int i=0;i<f[k].size();i++){
                // k 貰っている, 部分木sum = i 
                if(k>=b[id]){
                    chmax(res[i],f[k][i]);
                    chmax(res[i+1],f[k][i]);
                }else{
                    chmax(res[i],f[k][i]);
                    chmax(res[i+1],min(k - b[id],f[k][i]));
                }
            }
        }
        dp[id] = res;
    };
    dfs(dfs,0,-1);
    dbg(dp);
    int res = 0;
    for(int i=0;i<=n;i++){
        if(dp[0][i]>=0)res = i;
    }
    cout << res << endl;
    return 0;
}
accuracy: 1
time_ms: 220
memory_kb: 5700
final_rank: 7

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


template<typename T1,typename T2> bool chmin(T1 &a,T2 b){if(a<=b)return 0; a=b; return 1;}
template<typename T1,typename T2> bool chmax(T1 &a,T2 b){if(a>=b)return 0; a=b; return 1;}


const int MAX=(1<<30);

using Graph=vector<vector<int>>;

//要素数n 初期値x
template<typename T>
inline vector<T> vmake(size_t n,T x){
	return vector<T>(n,x);
}

//a,b,c,x data[a][b][c] 初期値x
template<typename... Args>
auto vmake(size_t n,Args... args){
	auto v=vmake(args...);
	return vector<decltype(v)>(n,move(v));
}

vector<int> A,B;
Graph g;
int N;
int MAX_B=500;

/*
返り値ret[i] := 
    頂点idxを根とした部分木で、宝をi個掘るとき、
        親に移動させることができる最大値 (ret[i]>0)
        親から移動してもらう最小値*-1 (ret[i]<0)
*/
vector<int> dfs(int idx,int par){
    //dp[下から貰う人数の合計(渡す人数は考えない)][下が掘る宝の数]=下とやり取りする人数の合計
    auto dp=vmake(MAX_B+1,N+1,-MAX);
    dp[0][0]=0;
    int MaxTreasure=0;
    for(int to:g[idx]){
        if(to==par) continue;
        vector<int> child=dfs(to,idx);
        
        vector<vector<int>> nex=vmake(MAX_B+1,N+1,-MAX);

        for(int b=0;b<=MAX_B;b++){
            for(int t0=0;t0<=MaxTreasure;t0++){
                for(int t1=0;t1<child.size();t1++){
                    if(dp[b][t0]==-MAX or child[t1]==-MAX) continue;
                    if(child[t1]>=0){
                        chmax(nex[min(B[idx],child[t1]+b)][t0+t1],dp[b][t0]+child[t1]);
                    }else{
                        chmax(nex[b][t0+t1],dp[b][t0]+child[t1]);                        
                    }
                }
            }
        }
        dp=nex;
        MaxTreasure+=child.size()-1;
    }
    auto ret=vmake(MaxTreasure+2,-MAX);
//ここから頂点idxの宝について考える
    for(int i=0;i<=MaxTreasure;i++){
        for(int b=0;b<=MAX_B;b++){
            if(A[idx]+b>=B[idx]){
                //頂点idxと親のやりとりの内容に関わらず、idxの宝を取れる
                chmax(ret[i+1],dp[b][i]+A[idx]);
            }else{
                chmax(ret[i+1],min(A[idx]+b-B[idx],dp[b][i]+A[idx]));
                chmax(ret[i],dp[b][i]+A[idx]); //idxの宝を諦める
            }
        }
    }
    for(int i=MaxTreasure-1;i>=0;i--){
        chmax(ret[i],ret[i+1]);
    }
    return ret;
}

void solve(){
    cin>>N;
    A.resize(N);
    B.resize(N);
    for(int i=0;i<N;i++){
        cin>>A[i];
    }
    for(int i=0;i<N;i++){
        cin>>B[i];
    }
    g.resize(N);
    for(int i=1;i<N;i++){
        int u,v;
        cin>>u>>v;
        u--; v--;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    vector<int> ans=dfs(0,-1);
    for(int i=N;i>=0;i--){
        if(ans[i]>=0){
            cout<<i<<endl;
            return;
        }
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout << fixed << setprecision(20);
    int T=1;
    //cin>>T;
    while(T--) solve();
}
accuracy: 1
time_ms: 390
memory_kb: 58940
final_rank: 9

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


template<typename T1,typename T2> bool chmin(T1 &a,T2 b){if(a<=b)return 0; a=b; return 1;}
template<typename T1,typename T2> bool chmax(T1 &a,T2 b){if(a>=b)return 0; a=b; return 1;}


const int MAX=(1<<30);

using Graph=vector<vector<int>>;

//要素数n 初期値x
template<typename T>
inline vector<T> vmake(size_t n,T x){
	return vector<T>(n,x);
}

//a,b,c,x data[a][b][c] 初期値x
template<typename... Args>
auto vmake(size_t n,Args... args){
	auto v=vmake(args...);
	return vector<decltype(v)>(n,move(v));
}

vector<int> A,B;
Graph g;
int N;

/*
返り値ret[i] := 
    頂点idxを根とした部分木で、宝をi個掘るとき、
        親に移動させることができる最大値 (ret[i]>0)
        親から移動してもらう最小値*-1 (ret[i]<0)
*/
vector<int> dfs(int idx,int par){
    //dp[下から貰う人数の合計(渡す人数は考えない)][下が掘る宝の数]=下とやり取りする人数の合計
    auto dp=vmake(B[idx]+1,N+1,-MAX);
    dp[0][0]=0;
    int MaxTreasure=0;
    for(int to:g[idx]){
        if(to==par) continue;
        vector<int> child=dfs(to,idx);
        
        vector<vector<int>> nex=vmake(B[idx]+1,N+1,-MAX);

        for(int b=0;b<=B[idx];b++){
            for(int t0=0;t0<=MaxTreasure;t0++){
                for(int t1=0;t1<child.size();t1++){
                    if(dp[b][t0]==-MAX or child[t1]==-MAX) continue;
                    if(child[t1]>=0){
                        chmax(nex[min(B[idx],child[t1]+b)][t0+t1],dp[b][t0]+child[t1]);
                    }else{
                        chmax(nex[b][t0+t1],dp[b][t0]+child[t1]);                        
                    }
                }
            }
        }
        dp=nex;
        MaxTreasure+=child.size()-1;
    }
    auto ret=vmake(MaxTreasure+2,-MAX);
//ここから頂点idxの宝について考える
    for(int i=0;i<=MaxTreasure;i++){
        for(int b=0;b<=B[idx];b++){
            if(A[idx]+b>=B[idx]){
                //頂点idxと親のやりとりの内容に関わらず、idxの宝を取れる
                chmax(ret[i+1],dp[b][i]+A[idx]);
            }else{
                chmax(ret[i+1],min(A[idx]+b-B[idx],dp[b][i]+A[idx]));
                chmax(ret[i],dp[b][i]+A[idx]); //idxの宝を諦める
            }
        }
    }
    for(int i=MaxTreasure-1;i>=0;i--){
        chmax(ret[i],ret[i+1]);
    }
    return ret;
}

void solve(){
    cin>>N;
    A.resize(N);
    B.resize(N);
    for(int i=0;i<N;i++){
        cin>>A[i];
    }
    for(int i=0;i<N;i++){
        cin>>B[i];
    }
    g.resize(N);
    for(int i=1;i<N;i++){
        int u,v;
        cin>>u>>v;
        u--; v--;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    vector<int> ans=dfs(0,-1);
    for(int i=N;i>=0;i--){
        if(ans[i]>=0){
            cout<<i<<endl;
            return;
        }
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout << fixed << setprecision(20);
    int T=1;
    //cin>>T;
    while(T--) solve();
}
accuracy: 1
time_ms: 380
memory_kb: 31224
final_rank: 8

code_snippet: #include "iostream"
#include "climits"
#include "list"
#include "queue"
#include "stack"
#include "set"
#include "functional"
#include "algorithm"
#include "string"
#include "map"
#include "unordered_map"
#include "unordered_set"
#include "iomanip"
#include "cmath"
#include "random"
#include "bitset"
#include "cstdio"
#include "numeric"
#include "cassert"
#include "ctime"

using namespace std;

//constexpr long long int MOD = 1000000007;
constexpr long long int MOD = 998244353;
constexpr double EPS = 1e-12;

//int N, M, K, T, H, W, L, R;
long long int N, M, K, T, H, W, L, R;

int ans = 0;
constexpr int maxB = 500;

void func(vector<int>& v, vector<int>& w, vector<vector<int>>& edge, vector<vector<int>>& dp, int node = 0, int p = -1) {
	bool leaf = true;
	vector<vector<int>>nxdp(2, vector<int>(maxB + 1, -MOD));
	nxdp[0][0] = 0;
	for (auto i : edge[node]) {
		if (i == p)continue;
		leaf = false;
		func(v, w, edge, dp, i, node);
		vector<vector<int>>nx(dp[i].size() + nxdp.size() - 1, vector<int>(maxB + 1, -MOD));
		for (int j = 0; j < nxdp.size(); j++) {
			for (int k = 0; k < dp[i].size(); k++) {
				for (int l = 0; l <= maxB; l++) {
					nx[j + k][min(maxB, max(0, dp[i][k]) + l)] = max(nx[j + k][min(maxB, max(0, dp[i][k]) + l)], nxdp[j][l] + dp[i][k]);
				}
			}
		}
		nxdp = nx;
	}

	if (leaf) {
		dp[node] = vector<int>(2, -MOD);
		if (v[node] >= w[node]) {
			dp[node][1] = v[node];
		}
		else {
			dp[node][0] = v[node];
			dp[node][1] = v[node] - w[node];
		}
	}
	else {
		dp[node].resize(nxdp.size(), -MOD);
		for (int i = 0; i < nxdp.size(); i++) {
			for (int j = 0; j <= maxB; j++) {
				if (nxdp[i][j] < -1000000)continue;
				//0
				dp[node][i] = max(dp[node][i], v[node] + nxdp[i][j]);
				//+1
				if (v[node] + j >= w[node]) {
					dp[node][i + 1] = max(dp[node][i + 1], v[node] + nxdp[i][j]);
				}
				else {
					dp[node][i + 1] = max(dp[node][i + 1], min(-w[node], nxdp[i][j]) + v[node] + j);
				}
			}
		}
	}

	return;
}

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

	cin >> N;
	vector<int>v(N);
	vector<int>w(N);
	for (auto& i : v)cin >> i;
	for (auto& i : w)cin >> i;

	vector<vector<int>>edge(N);
	for (int i = 1; i < N; i++) {
		cin >> L >> R;
		L--, R--;
		edge[L].push_back(R);
		edge[R].push_back(L);
	}
	vector<vector<int>>dp(N);
	func(v, w, edge, dp);
	for (int i = 0; i < dp[0].size(); i++) {
	//	cout << i << " " << dp[0][i] << endl;
		if (dp[0][i] >= 0)ans = i;
	}
	cout << ans << endl;
}
accuracy: 1
time_ms: 140
memory_kb: 6356
final_rank: 5