結果

問題 No.3755 Root for Your Route
コンテスト
ユーザー siganai
提出日時 2026-08-23 23:57:29
言語 C++17
(gcc 15.3.0 + boost 1.92.0 + ACL)
コンパイル:
g++-15 -O2 -lm -std=c++17 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 226 ms / 3,000 ms
+ 601µs
コード長 14,241 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 1,633 ms
コンパイル使用メモリ 240,776 KB
実行使用メモリ 40,984 KB
最終ジャッジ日時 2026-10-02 21:06:20
合計ジャッジ時間 10,075 ms
ジャッジサーバーID
(参考情報)
judge4_1 / judge2_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 39
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#line 1 "main.cpp"
#include<bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include <debug.hpp>
#define debug(...) debug_print::multi_print(#__VA_ARGS__, __VA_ARGS__)
#else
#define debug(...) (static_cast<void>(0))
#endif
//#pragma GCC target("avx,avx2")
//#pragma GCC optimize("O3")
//#pragma GCC optimize("unroll-loops")
using ll = long long;
using ull = unsigned long long;
using ld = long double;
using pll = pair<ll,ll>;
using pii = pair<int,int>;
using vi = vector<int>;
using vvi = vector<vi>;
using vvvi = vector<vvi>;
using vl = vector<ll>;
using vvl = vector<vl>;
using vvvl = vector<vvl>;
using vul = vector<ull>;
using vpii = vector<pii>;
using vvpii = vector<vpii>;
using vpll = vector<pll>;
using vvpll = vector<vpll>;
using vs = vector<string>;
template<class T> using pq = priority_queue<T,vector<T>, greater<T>>;
#define overload4(_1, _2, _3, _4, name, ...) name
#define overload3(a,b,c,name,...) name
#define rep1(n) for (ll UNUSED_NUMBER = 0; UNUSED_NUMBER < (n); ++UNUSED_NUMBER)
#define rep2(i, n) for (ll i = 0; i < (n); ++i)
#define rep3(i, a, b) for (ll i = (a); i < (b); ++i)
#define rep4(i, a, b, c) for (ll i = (a); i < (b); i += (c))
#define rep(...) overload4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)
#define rrep1(n) for(ll i = (n) - 1;i >= 0;i--)
#define rrep2(i,n) for(ll i = (n) - 1;i >= 0;i--)
#define rrep3(i,a,b) for(ll i = (b) - 1;i >= (a);i--)
#define rrep4(i,a,b,c) for(ll i = (a) + (((b)-(a)-1) / (c) - (((b)-(a)-1) % (c) && (((b)-(a)-1) ^ c) < 0)) * (c);i >= (a);i -= c)
#define rrep(...) overload4(__VA_ARGS__, rrep4, rrep3, rrep2, rrep1)(__VA_ARGS__)
#define all1(i) begin(i) , end(i)
#define all2(i,a) begin(i) , begin(i) + a
#define all3(i,a,b) begin(i) + a , begin(i) + b
#define all(...) overload3(__VA_ARGS__, all3, all2, all1)(__VA_ARGS__)
#define sum(...) accumulate(all(__VA_ARGS__),0LL)
template<class T> bool chmin(T &a, const T &b){ if(a > b){ a = b; return 1; } else return 0; }
template<class T> bool chmax(T &a, const T &b){ if(a < b){ a = b; return 1; } else return 0; }
template<class T> auto min(const T& a){return *min_element(all(a));}
template<class T> auto max(const T& a){return *max_element(all(a));}
template<class... Ts> void in(Ts&... t);
#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__)
#define LD(...) ld __VA_ARGS__; in(__VA_ARGS__)
#define VEC(type, name, size) vector<type> name(size); in(name)
#define VV(type, name, h, w) vector<vector<type>> name(h, vector<type>(w)); in(name)
ll intpow(ll a, ll b){ll ans = 1; while(b){if(b & 1) ans *= a; a *= a; b /= 2;} return ans;}
ll modpow(ll a, ll b, ll p){ ll ans = 1 % p; a %= p;if(a < 0) a += p;while(b){ if(b & 1) (ans *= a) %= p; (a *= a) %= p; b /= 2; } return ans; }
bool is_clamp(ll val,ll low,ll high) {return low <= val && val < high;}
void Yes() {cout << "Yes\n";return;}
void No() {cout << "No\n";return;}
void YES() {cout << "YES\n";return;}
void NO() {cout << "NO\n";return;}
template <typename U,typename T>
U floor(U a, T b) {return a / b - (a % b && (a ^ b) < 0);}
// ceil(x,y) = floor(x+y-1,y)なのでx+y-1がoverflowする可能性あり
template <typename U,typename T>
U ceil(U x, T y) {return floor(x + y - 1, y);}
template <typename U,typename T>
T bmod(U x, T y) {return x - y * floor(x, y);}
template <typename U,typename T>
pair<U, T> divmod(U x, T y) {U q = floor(x, y);return {q, x - q * y};}
namespace IO{
#define VOID(a) decltype(void(a))
struct setting{ setting(){cin.tie(nullptr); ios::sync_with_stdio(false);fixed(cout); cout.precision(15);}} setting;
template<int I> struct P : P<I-1>{};
template<> struct P<0>{};
template<class T> void i(T& t){ i(t, P<3>{}); }
void i(vector<bool>::reference t, P<3>){ int a; i(a); t = a; }
template<class T> auto i(T& t, P<2>) -> VOID(cin >> t){ cin >> t; }
template<class T> auto i(T& t, P<1>) -> VOID(begin(t)){ for(auto&& x : t) i(x); }
template<class T, size_t... idx> void ituple(T& t, index_sequence<idx...>){in(get<idx>(t)...);}
template<class T> auto i(T& t, P<0>) -> VOID(tuple_size<T>{}){ituple(t, make_index_sequence<tuple_size<T>::value>{});} 
#undef VOID
}
#define unpack(a) (void)initializer_list<int>{(a, 0)...}
template<class... Ts> void in(Ts&... t){ unpack(IO :: i(t)); }
#undef unpack
constexpr long double PI = 3.141592653589793238462643383279L;
template <class F> struct REC {
    F f;
    REC(F &&f_) : f(forward<F>(f_)) {}
    template <class... Args> auto operator()(Args &&...args) const { return f(*this, forward<Args>(args)...); }};

constexpr int mod = 998244353;
//constexpr int mod = 1000000007;

#line 2 "library/tree/CentroidDecomposition.hpp"
// root:根 tree:重心分解の探索する際に根となる順番 sub:探索する時の頂点数
template <typename G>
struct CentroidDecomposition {
    const G &g;
    vector<int> sub;
    vector<bool> v;
    vector<vector<int>> tree;
    int root;
    CentroidDecomposition(const G &g_, int isbuild = true) : g(g_) {
        sub.resize(g.size(), 0);
        v.resize(g.size(), false);
        if (isbuild) build();
    }
    void build() {
        tree.resize(g.size());
        root = build_dfs(0);
    }
    int get_size(int cur, int par) {
        sub[cur] = 1;
        for (auto &dst : g[cur]) {
            if (dst == par || v[dst]) continue;
            sub[cur] += get_size(dst, cur);
        }
        return sub[cur];
    }
    int get_centroid(int cur, int par, int mid) {
        for (auto &dst : g[cur]) {
            if (dst == par || v[dst]) continue;
            if (sub[dst] > mid) return get_centroid(dst, cur, mid);
        }
        return cur;
    }
    int build_dfs(int cur) {
        int centroid = get_centroid(cur, -1, get_size(cur, -1) / 2);
        v[centroid] = true;
        for (auto &dst : g[centroid]) {
            if (!v[dst]) {
                int nxt = build_dfs(dst);
                if (centroid != nxt) tree[centroid].emplace_back(nxt);
            }
        }
        v[centroid] = false;
        return centroid;
    }
};
#line 2 "library/data-structure/Dynamic-Li-Chao-Tree.hpp"

// 直線追加かつ非永続なら空間 O(Q)。
// 関数は ll -> T。[L, R) 上 f が overflow しないように注意。
// evaluate を書き変えると、totally monotone な関数群にも使える。
//
// 例:
// struct F {
//   using value_type = ll;
//   int a;
//   ll b;
//   ll operator()(ll x) { return a * x + b; }
// };
//
// Node は int 3つなので通常 12 byte。
// pool は vector で必要に応じて自動拡張される。
template <typename FUNC, bool PERSISTENT, bool MINIMIZE, long long INFINTY = 1LL << 60>
struct Dynamic_LiChao_Tree {
  using T = typename FUNC::value_type;
  using np = int;

  vector<FUNC> funcs;
  static inline T evaluate(FUNC &f, long long x) { return f(x); }

  struct Node {
    int fid;
    int l, r;
  };

  vector<Node> pool;
  long long L, R;

  Dynamic_LiChao_Tree(long long L, long long R) : L(L), R(R) {}
  Dynamic_LiChao_Tree() {}

  void reserve_nodes(size_t n) { pool.reserve(n); }
  void reserve_funcs(size_t n) { funcs.reserve(n); }
  int node_count() const { return (int)pool.size(); }
  size_t node_capacity() const { return pool.capacity(); }
  int func_count() const { return (int)funcs.size(); }

  void reset() {
    funcs.clear();
    pool.clear();
  }

  np new_root() const { return -1; }

  np chmin_line(np root, FUNC f) {
    static_assert(MINIMIZE);
    int fid = funcs.size();
    funcs.emplace_back(std::move(f));
    if (root == -1) root = new_node();
    return add_line_rec(root, fid, L, R);
  }

  np chmax_line(np root, FUNC f) {
    static_assert(!MINIMIZE);
    int fid = funcs.size();
    funcs.emplace_back(std::move(f));
    if (root == -1) root = new_node();
    return add_line_rec(root, fid, L, R);
  }

  // [xl, xr)
  np chmin_segment(np root, long long xl, long long xr, FUNC f) {
    static_assert(MINIMIZE);
    int fid = funcs.size();
    funcs.emplace_back(std::move(f));
    if (root == -1) root = new_node();
    return add_segment_rec(root, xl, xr, fid, L, R);
  }

  // [xl, xr)
  np chmax_segment(np root, long long xl, long long xr, FUNC f) {
    static_assert(!MINIMIZE);
    int fid = funcs.size();
    funcs.emplace_back(std::move(f));
    if (root == -1) root = new_node();
    return add_segment_rec(root, xl, xr, fid, L, R);
  }

  // (値・関数番号)
  pair<T, int> query(np root, long long x) {
    assert(L <= x && x < R);
    if (root == -1) {
      if constexpr (MINIMIZE) return {INFINTY, -1};
      else return {-INFINTY, -1};
    }
    return query_rec(root, x, L, R);
  }

private:
  np new_node(int fid = -1, int l = -1, int r = -1) {
    int id = pool.size();
    pool.push_back({fid, l, r});
    return id;
  }

  np copy_node(np c) {
    if constexpr (!PERSISTENT) return c;
    else {
      Node t = pool[c];
      int id = pool.size();
      pool.push_back(t);
      return id;
    }
  }

  inline T evaluate_inner(int fid, long long x) {
    if (fid == -1) {
      if constexpr (MINIMIZE) return INFINTY;
      else return -INFINTY;
    }
    return evaluate(funcs[fid], x);
  }

  np add_segment_rec(np c, long long xl, long long xr, int fid, long long node_l, long long node_r) {
    chmax(xl, node_l), chmin(xr, node_r);
    if (xl >= xr) return c;
    if (node_l < xl || xr < node_r) {
      c = copy_node(c);
      long long node_m = node_l + (node_r - node_l) / 2;
      int l = pool[c].l, r = pool[c].r;
      if (l == -1) l = new_node();
      if (r == -1) r = new_node();
      l = add_segment_rec(l, xl, xr, fid, node_l, node_m);
      r = add_segment_rec(r, xl, xr, fid, node_m, node_r);
      pool[c].l = l, pool[c].r = r;
      return c;
    }
    return add_line_rec(c, fid, node_l, node_r);
  }

  np add_line_rec(np c, int fid, long long node_l, long long node_r) {
    int gid = pool[c].fid;
    T fl = evaluate_inner(fid, node_l), fr = evaluate_inner(fid, node_r - 1);
    T gl = evaluate_inner(gid, node_l), gr = evaluate_inner(gid, node_r - 1);
    bool bl = (MINIMIZE ? fl < gl : fl > gl);
    bool br = (MINIMIZE ? fr < gr : fr > gr);

    if (bl && br) {
      c = copy_node(c);
      pool[c].fid = fid;
      return c;
    }
    if (!bl && !br) return c;

    c = copy_node(c);
    long long node_m = node_l + (node_r - node_l) / 2;
    T fm = evaluate_inner(fid, node_m), gm = evaluate_inner(gid, node_m);
    bool bm = (MINIMIZE ? fm < gm : fm > gm);

    if (bm) {
      pool[c].fid = fid;
      if (bl) {
        int r = pool[c].r;
        if (r == -1) r = new_node();
        pool[c].r = add_line_rec(r, gid, node_m, node_r);
      } else {
        int l = pool[c].l;
        if (l == -1) l = new_node();
        pool[c].l = add_line_rec(l, gid, node_l, node_m);
      }
    } else {
      if (!bl) {
        int r = pool[c].r;
        if (r == -1) r = new_node();
        pool[c].r = add_line_rec(r, fid, node_m, node_r);
      } else {
        int l = pool[c].l;
        if (l == -1) l = new_node();
        pool[c].l = add_line_rec(l, fid, node_l, node_m);
      }
    }
    return c;
  }

  pair<T, int> query_rec(np c, long long x, long long node_l, long long node_r) {
    int fid = pool[c].fid;
    pair<T, int> res = {evaluate_inner(fid, x), fid};
    long long node_m = node_l + (node_r - node_l) / 2;

    if (x < node_m) {
      int l = pool[c].l;
      if (l != -1) {
        auto res1 = query_rec(l, x, node_l, node_m);
        if constexpr (MINIMIZE) res = min(res, res1);
        else res = max(res, res1);
      }
    } else {
      int r = pool[c].r;
      if (r != -1) {
        auto res1 = query_rec(r, x, node_m, node_r);
        if constexpr (MINIMIZE) res = min(res, res1);
        else res = max(res, res1);
      }
    }
    return res;
  }
};
#line 103 "main.cpp"
struct F {
  using value_type = ll;  // operator() の戻り値
  ll a;
  ll b;
  ll operator()(ll x) { return a * x + b; }
};
void solve() {
    INT(n);
    VEC(int,a,n);
    vvi g(n);
    rep(i,n-1) {
        INT(u,v);
        u--,v--;
        g[u].emplace_back(v);
        g[v].emplace_back(u);
    }
    CentroidDecomposition CD(g);
    vl ans(n,-1e18);
    vi seen(n);
    Dynamic_LiChao_Tree<F,true,false> cht(0,n + 1);
    auto dfs1 = REC([&](auto &f1,int root) -> void {
        int cnt = 0;
        vi ver;
        rep(i,g[root].size()) {
            if(!seen[g[root][i]]) {
                ver.emplace_back(g[root][i]);
            }
        }
        vi Lnode(ver.size() + 1),Rnode(ver.size() + 1);
        int lnode = cht.new_root();
        Lnode[0] = lnode;
        auto dfs2 = REC([&](auto &f2,int now,int pre,int curnode,int d,ll su) -> int {
            curnode = cht.chmax_line(curnode,F{-d,su - 1LL * d * (d + 1) / 2});
            for(auto &nex:g[now]) {
                if(pre == nex || seen[nex]) continue;
                curnode = f2(nex,now,curnode,d + 1,su + a[nex]);
            }
            return curnode;
        });
        rep(i,ver.size()) {
            Lnode[i + 1] = dfs2(ver[i],root,Lnode[i],1,a[ver[i]]);
        }
        Rnode[ver.size()] = cht.new_root();
        rrep(i,ver.size()) {
            Rnode[i] = dfs2(ver[i],root,Rnode[i+1],1,a[ver[i]]);
        }
        auto dfs3 = REC([&](auto &f3,int now,int pre,int d,ll su,int id) -> ll {
            ll ret = su - 1LL * d * (d + 1) / 2;
            chmax(ret,cht.query(Lnode[id],d).first + su - 1LL * d * (d + 1) / 2);
            chmax(ret,cht.query(Rnode[id+1],d).first + su - 1LL * d * (d + 1) / 2);
            for(auto &nex:g[now]) {
                if(pre == nex || seen[nex]) continue;
                chmax(ret,f3(nex,now,d + 1,su + a[nex],id));
            }
            chmax(ans[now],ret);
            return ret;
        });
        ll rootret = a[root];
        rep(i,ver.size()) {
            chmax(rootret,dfs3(ver[i],root,1,a[root] + a[ver[i]],i));
        }
        chmax(ans[root],rootret);
        cht.reset();
        seen[root] = 1;
        for(auto &nex:CD.tree[root]) {
            f1(nex);
        }
    });
    dfs1(CD.root);
    debug(ans);
    cout << min(ans) << '\n';
}

int main() {
    int TT = 1;
    //cin >> TT;
    while(TT--) solve();
}
0