結果

問題 No.3193 Submit Your Solution
ユーザー ecottea
提出日時 2025-06-29 02:20:24
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 3,797 ms / 10,000 ms
コード長 30,285 bytes
コンパイル時間 7,985 ms
コンパイル使用メモリ 363,728 KB
実行使用メモリ 126,356 KB
最終ジャッジ日時 2025-06-29 02:21:12
合計ジャッジ時間 40,312 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 17
権限があれば一括ダウンロードができます

ソースコード

diff #

// QCFium 法
// #pragma GCC target("avx2") // yukicoder では消す
#pragma GCC optimize("O3") // たまにバグる
#pragma GCC optimize("unroll-loops")


#ifndef HIDDEN_IN_VS // 折りたたみ用

// 警告の抑制
#define _CRT_SECURE_NO_WARNINGS

// ライブラリの読み込み
#include <bits/stdc++.h>
using namespace std;

// 型名の短縮
using ll = long long; using ull = unsigned long long; // -2^63 ~ 2^63 = 9e18(int は -2^31 ~ 2^31 = 2e9)
using pii = pair<int, int>;	using pll = pair<ll, ll>;	using pil = pair<int, ll>;	using pli = pair<ll, int>;
using vi = vector<int>;		using vvi = vector<vi>;		using vvvi = vector<vvi>;	using vvvvi = vector<vvvi>;
using vl = vector<ll>;		using vvl = vector<vl>;		using vvvl = vector<vvl>;	using vvvvl = vector<vvvl>;
using vb = vector<bool>;	using vvb = vector<vb>;		using vvvb = vector<vvb>;
using vc = vector<char>;	using vvc = vector<vc>;		using vvvc = vector<vvc>;
using vd = vector<double>;	using vvd = vector<vd>;		using vvvd = vector<vvd>;
template <class T> using priority_queue_rev = priority_queue<T, vector<T>, greater<T>>;
using Graph = vvi;

// 定数の定義
const double PI = acos(-1);
int DX[4] = { 1, 0, -1, 0 }; // 4 近傍(下,右,上,左)
int DY[4] = { 0, 1, 0, -1 };
int INF = 1001001001; ll INFL = 4004004003094073385LL; // (int)INFL = INF, (int)(-INFL) = -INF;

// 入出力高速化
struct fast_io { fast_io() { cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(18); } } fastIOtmp;

// 汎用マクロの定義
#define all(a) (a).begin(), (a).end()
#define sz(x) ((int)(x).size())
#define lbpos(a, x) (int)distance((a).begin(), std::lower_bound(all(a), (x)))
#define ubpos(a, x) (int)distance((a).begin(), std::upper_bound(all(a), (x)))
#define Yes(b) {cout << ((b) ? "Yes\n" : "No\n");}
#define rep(i, n) for(int i = 0, i##_len = int(n); i < i##_len; ++i) // 0 から n-1 まで昇順
#define repi(i, s, t) for(int i = int(s), i##_end = int(t); i <= i##_end; ++i) // s から t まで昇順
#define repir(i, s, t) for(int i = int(s), i##_end = int(t); i >= i##_end; --i) // s から t まで降順
#define repe(v, a) for(const auto& v : (a)) // a の全要素(変更不可能)
#define repea(v, a) for(auto& v : (a)) // a の全要素(変更可能)
#define repb(set, d) for(int set = 0, set##_ub = 1 << int(d); set < set##_ub; ++set) // d ビット全探索(昇順)
#define repis(i, set) for(int i = lsb(set), bset##i = set; i < 32; bset##i -= 1 << i, i = lsb(bset##i)) // set の全要素(昇順)
#define repp(a) sort(all(a)); for(bool a##_perm = true; a##_perm; a##_perm = next_permutation(all(a))) // a の順列全て(昇順)
#define uniq(a) {sort(all(a)); (a).erase(unique(all(a)), (a).end());} // 重複除去
#define EXIT(a) {cout << (a) << endl; exit(0);} // 強制終了
#define inQ(x, y, u, l, d, r) ((u) <= (x) && (l) <= (y) && (x) < (d) && (y) < (r)) // 半開矩形内判定

// 汎用関数の定義
template <class T> inline ll powi(T n, int k) { ll v = 1; rep(i, k) v *= n; return v; }
template <class T> inline bool chmax(T& M, const T& x) { if (M < x) { M = x; return true; } return false; } // 最大値を更新(更新されたら true を返す)
template <class T> inline bool chmin(T& m, const T& x) { if (m > x) { m = x; return true; } return false; } // 最小値を更新(更新されたら true を返す)
template <class T> inline T getb(T set, int i) { return (set >> i) & T(1); }
template <class T> inline T smod(T n, T m) { n %= m; if (n < 0) n += m; return n; } // 非負mod

// 演算子オーバーロード
template <class T, class U> inline istream& operator>>(istream& is, pair<T, U>& p) { is >> p.first >> p.second; return is; }
template <class T> inline istream& operator>>(istream& is, vector<T>& v) { repea(x, v) is >> x; return is; }
template <class T> inline vector<T>& operator--(vector<T>& v) { repea(x, v) --x; return v; }
template <class T> inline vector<T>& operator++(vector<T>& v) { repea(x, v) ++x; return v; }

#endif // 折りたたみ用


#if __has_include(<atcoder/all>)
#include <atcoder/all>
using namespace atcoder;

#ifdef _MSC_VER
#include "localACL.hpp"
#endif

using mint = modint998244353;
//using mint = static_modint<(int)1e9 + 7>;
//using mint = modint; // mint::set_mod(m);

using vm = vector<mint>; using vvm = vector<vm>; using vvvm = vector<vvm>; using vvvvm = vector<vvvm>; using pim = pair<int, mint>;
#endif


#ifdef _MSC_VER // 手元環境(Visual Studio)
#include "local.hpp"
#else // 提出用(gcc)
int mute_dump = 0;
int frac_print = 0;
#if __has_include(<atcoder/all>)
namespace atcoder {
	inline istream& operator>>(istream& is, mint& x) { ll x_; is >> x_; x = x_; return is; }
	inline ostream& operator<<(ostream& os, const mint& x) { os << x.val(); return os; }
}
#endif
inline int popcount(int n) { return __builtin_popcount(n); }
inline int popcount(ll n) { return __builtin_popcountll(n); }
inline int lsb(int n) { return n != 0 ? __builtin_ctz(n) : 32; }
inline int lsb(ll n) { return n != 0 ? __builtin_ctzll(n) : 64; }
inline int msb(int n) { return n != 0 ? (31 - __builtin_clz(n)) : -1; }
inline int msb(ll n) { return n != 0 ? (63 - __builtin_clzll(n)) : -1; }
#define dump(...)
#define dumpel(v)
#define dump_math(v)
#define input_from_file(f)
#define output_to_file(f)
#define Assert(b) { if (!(b)) { vc MLE(1<<30); EXIT(MLE.back()); } } // RE の代わりに MLE を出す
#endif


//【グラフの入力】O(n + m)
/*
* (始点, 終点) の組からなる入力を受け取り,n 頂点 m 辺のグラフを構築して返す.
*
* n : グラフの頂点の数
* m : グラフの辺の数(省略すれば n-1)
* directed : 有向グラフか(省略すれば false)
* zero_indexed : 入力が 0-indexed か(省略すれば false)
*/
Graph read_Graph(int n, int m = -1, bool directed = false, bool zero_indexed = false) {
	// verify : https://atcoder.jp/contests/tessoku-book/tasks/tessoku_book_bi

	Graph g(n);
	if (m == -1) m = n - 1;

	rep(j, m) {
		int a, b;
		cin >> a >> b;
		if (!zero_indexed) { --a; --b; }

		g[a].push_back(b);
		if (!directed && a != b) g[b].push_back(a);
	}

	return g;
}


// お借りしました:
// https://noya2ruler.github.io/noya2_Library/tree/heavy_light_decomposition.hpp.html
namespace noya2 {

    struct hld_tree {
        int n, root;
        std::vector<int> down, nxt, sub, tour;
        // noya2::internal::csr<int> childs;

        // default constructor (nop)
        hld_tree() {}

        // tree with _n node
        // after construct, call input_edges / input_parents / add_edge _n - 1 times
        hld_tree(int _n, int _root = 0) : n(_n), root(_root), down(n), nxt(n), sub(n, 1), tour(n) {
            if (n == 1) {
                nxt[0] = -1;
                down[0] = -1;
                build_from_parents();
            }
        }

        // par[i] < i, par[0] == -1
        hld_tree(const std::vector<int>& par) : n(par.size()), root(0), down(n, -1), nxt(par), sub(n, 1), tour(n) {
            build_from_parents();
        }

        // par[i] < i, par[0] == -1
        hld_tree(std::vector<int>&& par) : n(par.size()), root(0), down(n, -1), sub(n, 1), tour(n) {
            nxt.swap(par);
            build_from_parents();
        }

        // distinct unweighted undirected n - 1 edges of tree 
        hld_tree(const std::vector<std::pair<int, int>>& es, int _root = 0) : n(es.size() + 1), root(_root), down(n), nxt(n), sub(n, 1), tour(n) {
            for (auto& [u, v] : es) {
                down[u]++;
                down[v]++;
                nxt[u] ^= v;
                nxt[v] ^= u;
            }
            build_from_edges();
        }

        // input parents from cin
        template<int indexed = 1>
        void input_parents() {
            // using std::cin;
            nxt[0] = -1;
            down[0] = -1;
            for (int u = 1; u < n; u++) {
                cin >> nxt[u];
                nxt[u] -= indexed;
                down[u] = -1;
            }
            build_from_parents();
        }

        // input n - 1 edges from cin
        template<int indexed = 1>
        void input_edges() {
            // using std::cin;
            for (int i = 1; i < n; i++) {
                int u, v; cin >> u >> v;
                u -= indexed;
                v -= indexed;
                down[u]++;
                down[v]++;
                nxt[u] ^= v;
                nxt[v] ^= u;
            }
            build_from_edges();
        }

        void add_edge(int u, int v) {
            down[u]++;
            down[v]++;
            nxt[u] ^= v;
            nxt[v] ^= u;
            // use tour[0] as counter
            if (++tour[0] == n - 1) {
                build_from_edges();
            }
        }

        size_t size() const {
            return n;
        }

        // top vertex of heavy path which contains v
        int leader(int v) const {
            return nxt[v] < 0 ? v : nxt[v];
        }

        // level ancestor
        // ret is ancestor of v, dist(ret, v) == d
        // if d > depth(v), return -1
        int la(int v, int d) const {
            while (v != -1) {
                int u = leader(v);
                if (down[v] - d >= down[u]) {
                    v = tour[down[v] - d];
                    break;
                }
                d -= down[v] - down[u] + 1;
                v = (u == root ? -1 : ~nxt[u]);
            }
            return v;
        }

        // lowest common ancestor of u and v
        int lca(int u, int v) const {
            int du = down[u], dv = down[v];
            if (du > dv) {
                std::swap(du, dv);
                std::swap(u, v);
            }
            if (dv < du + sub[u]) {
                return u;
            }
            while (du < dv) {
                v = ~nxt[leader(v)];
                dv = down[v];
            }
            return v;
        }

        // distance from u to v
        int dist(int u, int v) const {
            int _dist = 0;
            while (leader(u) != leader(v)) {
                if (down[u] > down[v]) std::swap(u, v);
                _dist += down[v] - down[leader(v)] + 1;
                v = ~nxt[leader(v)];
            }
            _dist += std::abs(down[u] - down[v]);
            return _dist;
        }

        // d times move from to its neighbor (direction of to)
        // if d > dist(from, to), return -1
        int jump(int from, int to, int d) const {
            int _from = from, _to = to;
            int dist_from_lca = 0, dist_to_lca = 0;
            while (leader(_from) != leader(_to)) {
                if (down[_from] > down[_to]) {
                    dist_from_lca += down[_from] - down[leader(_from)] + 1;
                    _from = ~nxt[leader(_from)];
                }
                else {
                    dist_to_lca += down[_to] - down[leader(_to)] + 1;
                    _to = ~nxt[leader(_to)];
                }
            }
            if (down[_from] > down[_to]) {
                dist_from_lca += down[_from] - down[_to];
            }
            else {
                dist_to_lca += down[_to] - down[_from];
            }
            if (d <= dist_from_lca) {
                return la(from, d);
            }
            d -= dist_from_lca;
            if (d <= dist_to_lca) {
                return la(to, dist_to_lca - d);
            }
            return -1;
        }

        // parent of v (if v is root, return -1)
        int parent(int v) const {
            if (v == root) return -1;
            return (nxt[v] < 0 ? ~nxt[v] : tour[down[v] - 1]);
        }

        // visiting time in euler tour
        // usage : seg.set(index(v), X[v])
        int index(int vertex) const {
            return down[vertex];
        }
        // usage : seg.set(index_edge(e.u, e.v), e.val)
        int index(int vertex1, int vertex2) const {
            return std::max(down[vertex1], down[vertex2]);
        }

        // subtree size of v
        int subtree_size(int v) const {
            return sub[v];
        }

        // prod in subtree v : seg.prod(subtree_l(v), subtree_r(v))
        int subtree_l(int v) const {
            return down[v];
        }
        int subtree_r(int v) const {
            return down[v] + sub[v];
        }

        // v is in subtree r
        bool is_in_subtree(int r, int v) const {
            return subtree_l(r) <= subtree_l(v) && subtree_r(v) <= subtree_r(r);
        }

        // distance table from s
        std::vector<int> dist_table(int s) const {
            std::vector<int> table(n, -1);
            table[s] = 0;
            while (s != root) {
                table[parent(s)] = table[s] + 1;
                s = parent(s);
            }
            for (int v : tour) {
                if (table[v] == -1) {
                    table[v] = table[parent(v)] + 1;
                }
            }
            return table;
        }

        // dist, v1, v2
        std::tuple<int, int, int> diameter() const {
            std::vector<int> dep = dist_table(root);
            int v1 = std::ranges::max_element(dep) - dep.begin();
            std::vector<int> fromv1 = dist_table(v1);
            int v2 = std::ranges::max_element(fromv1) - fromv1.begin();
            return { fromv1[v2], v1, v2 };
        }

        // vertex array {from, ..., to}
        std::vector<int> path(int from, int to) const {
            int d = dist(from, to);
            std::vector<int> _path(d + 1);
            int front = 0, back = d;
            while (from != to) {
                if (down[from] > down[to]) {
                    _path[front++] = from;
                    from = parent(from);
                }
                else {
                    _path[back--] = to;
                    to = parent(to);
                }
            }
            _path[front] = from;
            return _path;
        }

        // path decomposition and query (vertex weighted)
        // if l < r, decsending order tour[l, r)
        // if l > r, acsending order tour(l, r]
        template<bool vertex = true>
        void path_query(int u, int v, auto f) const {
            while (leader(u) != leader(v)) {
                if (down[u] < down[v]) {
                    f(down[leader(v)], down[v] + 1);
                    v = ~nxt[leader(v)];
                }
                else {
                    f(down[u] + 1, down[leader(u)]);
                    u = ~nxt[leader(u)];
                }
            }
            if constexpr (vertex) {
                if (down[u] < down[v]) {
                    f(down[u], down[v] + 1);
                }
                else {
                    f(down[u] + 1, down[v]);
                }
            }
            else {
                if (down[u] != down[v]) {
                    f(down[u] + 1, down[v] + 1);
                }
            }
        }

        // {parent, mapping} : cptree i is correspond to tree mapping[i]. parent[i] is parent of i in cptree.
        // parent[i] < i, parent[0] == -1
        std::pair<std::vector<int>, std::vector<int>> compressed_tree(std::vector<int> vs) const {
            if (vs.empty()) {
                return { {},{} };
            }
            auto comp = [&](int l, int r) {
                return down[l] < down[r];
            };
            std::ranges::sort(vs, comp);
            int sz = vs.size(); vs.reserve(2 * sz);
            for (int i = 0; i < sz - 1; i++) {
                vs.emplace_back(lca(vs[i], vs[i + 1]));
            }
            std::sort(vs.begin() + sz, vs.end(), comp);
            std::ranges::inplace_merge(vs, vs.begin() + sz, comp);
            auto del = std::ranges::unique(vs);
            vs.erase(del.begin(), del.end());
            sz = vs.size();
            std::stack<int> st;
            std::vector<int> par(sz);
            par[0] = -1;
            st.push(0);
            for (int i = 1; i < sz; i++) {
                while (!is_in_subtree(vs[st.top()], vs[i])) st.pop();
                par[i] = st.top();
                st.push(i);
            }
            return { par, vs };
        }

        /*  CSR

            // build csr for using operator()
            void build_csr(){
                childs = noya2::internal::csr<int>(n, n - 1);
                for (int v = 0; v < n; v++){
                    if (v == root) continue;
                    childs.add(parent(v), v);
                }
                childs.build();
            }
            const auto operator()(int v) const {
                return childs[v];
            }
            auto operator()(int v){
                return childs[v];
            }
        */

        // hld_tree g;
        // euler tour order : `for (int v : g)`
        // with range_adaptor : `for (int v : g | std::views::reverse)`
        // bottom-up DP : `for (int v : g | std::views::drop(1) | std::views::reverse){ update dp[g.parent(v)] by dp[v] }`
        auto begin() const {
            return tour.begin();
        }
        auto end() const {
            return tour.end();
        }

    private:
        // nxt[v] : parent of v, nxt[0] == -1
        void build_from_parents() {
            for (int u = n - 1; u >= 1; u--) {
                int v = nxt[u];
                sub[v] += sub[u];
                down[v] = std::max(down[v], sub[u]);
            }
            for (int u = n - 1; u >= 1; u--) {
                int v = nxt[u];
                if (down[v] == sub[u]) {
                    sub[u] = ~sub[u];
                    down[v] = ~down[v];
                }
            }

            sub[0] = ~down[0] + 1;
            down[0] = 0;
            for (int u = 1; u < n; u++) {
                int v = nxt[u];
                int nsub = ~down[u] + 1;
                if (sub[u] < 0) {
                    down[u] = down[v] + 1;
                    nxt[u] = (nxt[v] < 0 ? v : nxt[v]);
                }
                else {
                    down[u] = down[v] + sub[v];
                    sub[v] += sub[u];
                    nxt[u] = ~v;
                }
                sub[u] = nsub;
            }

            for (int u = 0; u < n; u++) {
                tour[down[u]] = u;
            }
        }

        // down[v] : degree of v
        // nxt[v] : xor prod of neighbor of v
        void build_from_edges() {
            // use tour as queue
            int back = 0;
            for (int u = 0; u < n; u++) {
                if (u != root && down[u] == 1) {
                    tour[back++] = u;
                }
            }
            for (int front = 0; front < n - 1; front++) {
                int u = tour[front];
                down[u] = -1;
                int v = nxt[u]; // parent of v
                nxt[v] ^= u;
                if (--down[v] == 1 && v != root) {
                    tour[back++] = v;
                }
            }
            // check : now, tour is reverse of topological order

            tour.pop_back();

            // check : now, down[*] <= 1
            for (int u : tour) {
                int v = nxt[u];
                // subtree size (initialized (1,1,...,1))
                sub[v] += sub[u];
                // heaviest subtree of its child
                down[v] = std::max(down[v], sub[u]);
            }
            for (int u : tour) {
                int v = nxt[u];
                // whether u is not the top of heavy path
                if (down[v] == sub[u]) {
                    sub[u] = ~sub[u];
                    down[v] = ~down[v];
                }
            }

            // after appearing v as u (or v == root), 
            // down[v] is the visiting time of euler tour
            // nxt[v] is the lowest vertex of heavy path which contains v
            //   (if v itself, nxt[v] is ~(parent of v))
            // sub[v] + down[v] is the light child's starting time of euler tour
            // note : heavy child's visiting time of euler tour is (the time of its parent) + 1
            sub[root] = ~down[root] + 1;
            down[root] = 0;
            nxt[root] = -1;
            for (int u : tour | std::views::reverse) {
                int v = nxt[u];
                int nsub = ~down[u] + 1;
                // heavy child
                if (sub[u] < 0) {
                    down[u] = down[v] + 1;
                    nxt[u] = (nxt[v] < 0 ? v : nxt[v]);
                }
                // light child
                else {
                    down[u] = down[v] + sub[v];
                    sub[v] += sub[u];
                    nxt[u] = ~v;
                }
                sub[u] = nsub;
            }

            // tour is inverse permutation of down
            tour.push_back(0);
            for (int u = 0; u < n; u++) {
                tour[down[u]] = u;
            }
        }
    };

} // namespace noya2


//【static top tree】
/*
* Static_top_tree<F, get_fnc, rake, comp>(Graph g, int r) : O(n (log n)^2)
*	r を根とする根付き木 g で初期化する.
*
* set(int s) : O((log n)^2)
*	頂点 s の情報の更新を反映する.
*
* F get() : O(1)
*	根付き木全体に対応する関数を返す.
*
* なおテンプレート引数が表す関数は以下の通りとする:
*
* F get_fnc(int s) :
*   生きた葉 s とその仮の親 p'(開頂点)のみからなる開部分木に対応する関数 f を返す.
*	開部分木 t に対応する関数が g であるとき,t を s に結合した開部分木の関数が f o g になるようにする.
*
* F rake(F f, F g) :
*   開部分木 s, t に対応する関数が f, g のとき,開部分木の開根を重ねた開部分木に対する関数を返す.
*	その際 g の生きた葉は死に関数としての能力を失うので 2 変数関数になるわけではない.
*
* F comp(F f, F g) :
*	合成関数 f o g を返す.
*/
template <class F, F(*get_fnc)(int), F(*rake)(const F&, const F&), F(*comp)(const F&, const F&)>
class Static_top_tree {
    // 参考 : https://atcoder.jp/contests/abc351/editorial/9868

    struct Node {
        // tp : ノードのタイプ
        //	R:rake, C:comp, f:leaf
        char tp = '?';

        // id : heavy path ならその根,light child ならその長男
        int id = -1;

        // [l..r) : heavy path, light child 共にどの範囲を見ているか
        int l = -1, r = -1;

        // pp : 親ノードへのポインタ,lp[rp] : 左[右]の子ノードへのポインタ
        Node* pp = nullptr, * lp = nullptr, * rp = nullptr;

        // f : 関数
        F f;

        // 参考 : https://qiita.com/tubo28/items/f058582e457f6870a800
        static inline int node_count = 0;
        // 静的に確保した配列から返す
        void* operator new(std::size_t) {
            constexpr int MAX_N = (int)2e5 * 2 + 10; // 2 倍居る
            static Node pool[MAX_N];
            return pool + node_count++;
        }
    };

    // root : 根(根付き木全体に対応する)
    Node* root;

    // st[s] : 頂点 s の変更があったとき,どのノードから更新を始めればいいか
    vector<Node*> st;

public:
    // rt を根とする根付き木 g で初期化する.
    Static_top_tree(const Graph& g, int rt) {
        // verify : https://judge.yosupo.jp/problem/point_set_tree_path_composite_sum_fixed_root

        int n = sz(g);

        // j_max[s] : s の重さ最大の部分木が何番目か
        vi j_max(n, -1);

        // 部分木の重さを調べる.
        function<int(int, int)> dfs_wgt = [&](int s, int p) {
            int ws = 0; int wt_max = -INF;

            rep(j, sz(g[s])) {
                auto t = g[s][j];
                if (t == p) continue;

                int wt = dfs_wgt(t, s);
                ws += wt + 1;
                if (chmax(wt_max, wt)) j_max[s] = j;
            }
            return ws;
        };
        dfs_wgt(rt, -1);

        // hp[s] : 根を s とする heavy path を成す頂点の列(深さ降順)
        vvi hp(n);

        // lc[s] : 頂点 s の兄弟である light child のリスト(自身を lc[s][0] に含む)
        vvi lc(n);

        // HL 分解を行う.
        function<void(int, int, int)> dfs_hld = [&](int s, int p, int r) {
            hp[r].push_back(s);

            int ht = -1;

            if (j_max[s] != -1) {
                ht = g[s][j_max[s]];
                lc[ht].push_back(ht);

                dfs_hld(ht, s, r);
            }

            rep(j, sz(g[s])) {
                int t = g[s][j];
                if (t == p || j == j_max[s]) continue;

                lc[ht].push_back(t);

                dfs_hld(t, s, t);
            }
        };
        dfs_hld(rt, -1, rt);

        root = new Node{ 'C', rt, 0, sz(hp[rt]) };
        st.resize(n);

        // トップダウンに二分木を構築する.
        function<void(Node*)> dfs_btree = [&](Node* p) {
            // 仮ラベルが 'C'
            if (p->tp == 'C') {
                // ラベルが 'C'
                if (p->r - p->l >= 2) {
                    int m = (p->l + p->r) / 2;

                    p->lp = new Node{ 'C', p->id, p->l, m, p };
                    dfs_btree(p->lp);

                    p->rp = new Node{ 'C', p->id, m, p->r, p };
                    dfs_btree(p->rp);

                    p->f = comp(p->lp->f, p->rp->f);
                }
                // ラベルが 'R' か 'L'
                else {
                    p->id = hp[p->id][p->l]; // light child の長男の頂点番号
                    p->l = 0;
                    p->r = sz(lc[p->id]);

                    if (p->r <= 1) {
                        p->tp = 'f';
                        p->f = get_fnc(p->id);
                        st[p->id] = p;
                    }
                    else {
                        p->tp = 'R';
                        dfs_btree(p);
                    }
                }
            }
            // 仮ラベルが 'R'
            else if (p->tp == 'R') {
                // ラベルが 'R'
                if (p->r - p->l >= 2) {
                    int m = (p->l + p->r) / 2;

                    p->lp = new Node{ 'R', p->id, p->l, m, p };
                    dfs_btree(p->lp);

                    p->rp = new Node{ 'R', p->id, m, p->r, p };
                    dfs_btree(p->rp);

                    p->f = rake(p->lp->f, p->rp->f);
                }
                // ラベルが 'C' か 'L'
                else {
                    p->id = lc[p->id][p->l]; // heavy path の根の頂点番号
                    p->l = 0;
                    p->r = sz(hp[p->id]);

                    if (p->r <= 1) {
                        p->tp = 'f';
                        p->f = get_fnc(p->id);
                        st[p->id] = p;
                    }
                    else {
                        p->tp = 'C';
                        dfs_btree(p);
                    }
                }
            }
        };
        dfs_btree(root);
    }

    // 頂点 s の情報の更新を反映する.
    void set(int v) {
        // verify : https://judge.yosupo.jp/problem/point_set_tree_path_composite_sum_fixed_root

        Node* p = st[v];

        // ボトムアップに必要な箇所のみ更新する.
        while (p) {
            if (p->tp == 'R') {
                p->f = rake(p->lp->f, p->rp->f);
            }
            else if (p->tp == 'C') {
                p->f = comp(p->lp->f, p->rp->f);
            }
            else if (p->tp == 'f') {
                p->f = get_fnc(p->id);
            }

            p = p->pp;
        }
    }

    // 根付き木全体の関数を返す.
    F get() {
        // verify : https://judge.yosupo.jp/problem/point_set_tree_path_composite_sum_fixed_root

        return root->f;
    }

    /* 雛形(値属性と関数属性を行ったり来たりしてややこしいので自動生成すべき)
    struct F {
    mint a, b;
    };
    F get_fnc(int i) {
        return F{ 1, a[i] };
    }
    F rake(const F& f, const F& g) {
        return F{ f.a * g.b, f.b * g.b };
    }
    F comp(const F& f, const F& g) {
        return F{ f.a * g.a, f.a * g.b + f.b };
    }
    Static_top_tree<F, get_fnc, rake, comp> G(g, 0);
    */
};


// 面倒になったので自動生成.変数名がカス.
vi col;
using F = array<ull, 10>;
F get_fnc(int s) {
    if (col[s] == 0) {
        return F{ 1, 1, 1, 0, 0, 0, 0, 0, 1, 0 };
    }
    else {
        return F{ 1, 0, 0, 1, 1, 0, 1, 0, 0, 0 };
    }
}
F rake(const F& f, const F& g) {
    auto [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10] = f;
    auto [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10] = g;

    return F{ f1, f2 + g2, f3 + g3, f4 + g4, f5 + g5, f6 + f1 * g4 + g5, f7 + g4, f8 + f1 * g2 + g3, f9 + g2, f10 + g10 + f5 * g2 + f4 * g3 + f3 * g4 + f2 * g5 };
}
F comp(const F& f, const F& g) {
    auto [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10] = f;
    auto [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10] = g;

    return F{ f1 + g1, f2 + g2, f3 + f1 * g2 + g3, f4 + g4, f5 + f1 * g4 + g5, f6 + f7 * g1 + g6, f7 + g7, f8 + f9 * g1 + g8, f9 + g9, f10 + g10 + f6 * g2 + f7 * g3 + f8 * g4 + f9 * g5 };
}


int main() {
//	input_from_file("input.txt");
//	output_to_file("output.txt");

	int n;
	cin >> n;
    	
    noya2::hld_tree g(n, 0);
    rep(j, n - 1) {
        int u, v;
        cin >> u >> v;
        u--; v--;

        g.add_edge(u, v);
    }

    auto g2 = read_Graph(n);

	vvi on(n), off(n);

	repi(i, 0, n - 1) {
        g.path_query(0, i, [&](int l, int r) {
            if (l > r) std::swap(l, r);
            on[l].push_back(i);
            off[r - 1].push_back(i);
        });
	}
	dumpel(on); dumpel(off);

	col = vi(n, 0);
	
	ull res = 0;

    // ボトルネックはこいつだろうけど,せっかくなので爆速 HLD を体験させていただく.
    Static_top_tree<F, get_fnc, rake, comp> STT(g2, 0);

	rep(t, n) {
		dump("------------- t:", t, "--------------");

		repe(i, on[t]) {
			col[i] = 1;
			STT.set(i);
		}
		dump("col:", col);

		auto pres = res;
		res += STT.get()[9];
		dump(res - pres);

		repe(i, off[t]) {
			col[i] = 0;
			STT.set(i);
		}
	}

	res *= 2;

	EXIT(res); // これが遅かったのも誤差の範囲?
}
0