結果

問題 No.3194 Do Optimize Your Solution
ユーザー ecottea
提出日時 2025-06-29 23:40:09
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 2,444 ms / 3,000 ms
コード長 24,961 bytes
コンパイル時間 6,060 ms
コンパイル使用メモリ 313,244 KB
実行使用メモリ 99,372 KB
最終ジャッジ日時 2025-06-29 23:40:45
合計ジャッジ時間 29,494 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
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;
}


//【貰う木 DP】O(n)
/*
* 与えられた r を根とする根付き木 g に対し,各頂点 s∈[0..n) について,
* 部分木 s に関する問題の答えを格納したリストを返す.
*
* T leaf(int s) :
*   葉 s のみからなる部分木についての答えを返す.
*
* T add_edge(T x, int p, int s) :
*   部分木 s についての暫定の答えが x のとき,
*   辺 p'→s を追加した部分木 p' についての答えを返す(記号 ' は仮の頂点を表す)
*
* void merge(T& x, T y, int s) :
*   仮の根 s' を共有する部分木 2 つに対する答えがそれぞれ x, y のとき,
*   x 側に y 側をマージして部分木 s' についての答えを x に上書きする.
*
* void add_vertex(T& x, int s) :
*	仮の根 s' をもつ部分木 s' に対する答えが x のとき,
*	根 s を追加した部分木 s についての答えを x に上書きする.
*/
template <class T, T(*leaf)(int), T(*add_edge)(const T&, int, int), void(*merge)(T&, const T&, int), void(*add_vertex)(T&, int)>
vector<T> tree_getDP(const Graph& g, int r) {
	// verify : https://atcoder.jp/contests/tdpc/tasks/tdpc_eel

	int n = sz(g);
	vector<T> dp(n);

	// 部分木 s についての答えを計算する.(p : s の親)
	function<void(int, int)> dfs = [&](int s, int p) {
		// is_leaf : s が葉か
		bool is_leaf = true;

		repe(t, g[s]) {
			if (t == p) continue;

			// 部分木 t についての答えを計算する.
			dfs(t, s);

			// 部分木 t に対して辺 s'→t を追加した場合の部分木 s' についての答えを得る.
			T sub = add_edge(dp[t], s, t);

			// それを部分木 s' の暫定の答えとマージして答えを更新していく.
			if (is_leaf) dp[s] = move(sub);
			else merge(dp[s], sub, s);

			is_leaf = false;
		}

		// s が葉の場合は専用の答えを代入しておく.
		if (is_leaf) dp[s] = leaf(s);
		// そうでない場合は根 s を追加する.
		else add_vertex(dp[s], s);
	};
	dfs(r, -1);

	return dp;

	/* 雛形
	struct T {
		int v;
	#ifdef _MSC_VER
		friend ostream& operator<<(ostream& os, const T& x) {
			os << '(' << x.v << ')';
			return os;
		}
	#endif
	};
	T leaf(int s) {
		return T{ 1 };
	}
	T add_edge(const T& x, int p, int s) {
		return x;
	}
	void merge(T& x, const T& y, int s) {
		x.v += y.v;
	}
	void add_vertex(T& x, int s) {
		x.v += 1;
	}
	vector<T> solve_by_tree_getDP(const Graph& g, int r) {
		return tree_getDP<T, leaf, add_edge, merge, add_vertex>(g, r);
	}
	*/
};


int col[200000];
struct T {
	ull c0, s0, c1, s1, s01;
#ifdef _MSC_VER
	friend ostream& operator<<(ostream& os, const T& x) {
		os << '(' << x.c0 << "," << x.s0 << "," << x.c1 << "," << x.s1 << "," << x.s01 << ')';
		return os;
	}
#endif
};
T leaf(int s) {
	if (col[s] == 0) {
		return T{ 1, 0, 0, 0, 0 };
	}
	else {
		return T{ 0, 0, 1, 0, 0 };
	}
}
T add_edge(const T& x, int p, int s) {
	auto [c0, s0, c1, s1, s01] = x;

	return T{ c0, s0 + c0, c1, s1 + c1, s01 };
}
void merge(T& x, const T& y, int s) {
	auto [x_c0, x_s0, x_c1, x_s1, x_s01] = x;
	auto [y_c0, y_s0, y_c1, y_s1, y_s01] = y;

	T z;
	z.c0 = x_c0 + y_c0;
	z.s0 = x_s0 + y_s0;
	z.c1 = x_c1 + y_c1;
	z.s1 = x_s1 + y_s1;
	z.s01 = x_s01 + y_s01 + x_c0 * y_s1 + x_s0 * y_c1 + x_c1 * y_s0 + x_s1 * y_c0;

	x = move(z);
}
void add_vertex(T& x, int s) {
	if (col[s] == 0) {
		x.c0++;
		x.s01 += x.s1;
	}
	else {
		x.c1++;
		x.s01 += x.s0;
	}
}
vector<T> solve_by_tree_getDP(const Graph& g, int r) {
	return tree_getDP<T, leaf, add_edge, merge, add_vertex>(g, r);
}



//【[部分木,パス]頂点加算/[部分木,パス]頂点総和(Z-加群)】(の改変)
/*
* Vertex_add_sum_query<S, op, o, inv, mul>(Graph g, int rt) : O(n)
*	rt を根とする根付き木 g と頂点値 v[0..n) = o() で初期化する.
*	要素は Z-加群 (S, op, o, inv, mul) の元とする.
*
* Vertex_add_sum_query<S, op, o, inv, mul>(Graph g, int rt, vS a) : O(n)
*	rt を根とする根付き木 g と頂点値 v[0..n) = a[0..n) で初期化する.
*
* set(int s, S x) : O(log n)
*	v[s] = x とする.
*
* S get(int s) : O(log n)
*	v[s] を返す.
*
* S sum_subtree(int s) : O(log n)
*	部分木 s の頂点の値の総和を返す.
*
* S sum_path(int s, int t) : O((log n)^2)
*	パス s→t 上の頂点(両端含む)の値の総和を返す.
*
* add(int s, S x) : O(log n)
*	v[s] += x とする.
*
* add_subtree(int v, S x) : O(log n)
*	部分木 s の頂点の値に x を加算する.
*
* add_path(int s, int t, S x) : O((log n)^2)
*	パス s→t 上の頂点(両端含む)の値に x を加算する.
*
* 利用:【区間加算フェニック木(Z-加群)】
*/
class Vertex_add_sum_query {
	// 参考:https://qiita.com/Pro_ktmr/items/4e1e051ea0561772afa3

	int n;

	// in[s]  : 根からの DFS で頂点 s に最初に入った時刻
	// out[s] : 根からの DFS で頂点 s から最後に出た時刻
	// top[s] : 頂点 s を含む heavy path の最も浅い頂点
	// wgt[s] : 頂点 s の重さ(部分木 s のもつ辺の数)
	// p[s] : 頂点 s の親
	vi in, out, top, wgt, p;

	// v[i] :  時刻 t に居た頂点の値

	// 各頂点の重さと親を求めるための DFS を行う.
	void dfs1(const Graph& g, int rt) {
		function<void(int)> rf = [&](int s) {
			repe(t, g[s]) {
				if (t == p[s]) continue;
				p[t] = s;
				rf(t);
				wgt[s] += wgt[t] + 1;
			}
		};
		p[rt] = -1;
		rf(rt);
	};

	// 最も重い子を優先して DFS を行う.
	void dfs2(const Graph& g, int rt) {
		int time = 0;

		function<void(int, int)> rf = [&](int s, int tp) {
			in[s] = time;
			top[s] = tp;
			time++;

			// 重さ最大の頂点を得る.
			int w_max = -INF, t_max = -1;
			repe(t, g[s]) {
				if (t == p[s]) continue;
				if (chmax(w_max, wgt[t])) t_max = t;
			}

			// 重さ最大の頂点を優先的になぞる.
			if (t_max != -1) rf(t_max, tp);

			// 残りの頂点をなぞる.
			repe(t, g[s]) {
				if (t == p[s] || t == t_max) continue;
				rf(t, t);
			}

			// s から最後に離れる
			out[s] = time;
		};
		rf(rt, rt);
	}

public:
	// rt を根とする根付き木 g と頂点値 v[0..n) = o で初期化する.
	Vertex_add_sum_query(const Graph& g, int rt) : n(sz(g)), in(n), out(n), top(n), wgt(n), p(n) {
		// verify : https://www.codechef.com/problems/HEALTHYTREE
		dfs1(g, rt);
		dfs2(g, rt);
	}

	Vertex_add_sum_query() : n(0) {}

	// パス s→t 上の頂点(両端含む)の値の総和を返す.
	vector<pii> sum_path(int s, int t) const {
		// verify : https://judge.yosupo.jp/problem/vertex_add_path_sum

		vector<pii> res;

		// s と t が異なる連結成分に属している限りループを回す.
		while (top[s] != top[t]) {
			// s の方が浅い連結成分に属しているとする.
			if (in[top[s]] > in[top[t]]) swap(s, t);

			// t を含む連結成分は v で並んで配置されているので,
			// 最も浅い頂点 top[t] から t までの範囲の和を求める.
			//res = op(res, v.sum(in[top[t]], in[t] + 1));
			res.push_back({ in[top[t]], in[t] + 1 });

			// 一つ浅い連結成分に移動する.
			t = p[top[t]];
		}

		// ここまできたら s と t は同じ連結成分に属するので,
		// その間の頂点のみの和を res に加算する.
		if (in[s] > in[t]) swap(s, t);
		//res = op(res, v.sum(in[s], in[t] + 1));
		res.push_back({ in[s], in[t] + 1 });

		return res;
	}
};


ull TLE(int n, Graph g, Graph g2) {
	Vertex_add_sum_query G(g, 0);

	vvi on(n), off(n);

	repi(i, 0, n - 1) {
		auto lrs = G.sum_path(0, i);
		//dump(i, ":", lrs);

		for (auto [l, r] : lrs) {
			on[l].push_back(i);
			off[r - 1].push_back(i);
		}
	}
	//dumpel(on); dumpel(off);

	rep(i, n) col[i] = 0;

	ull res = 0;

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

		repe(i, on[t]) col[i] = 1;
		//dump("col:", col);

		auto dp = solve_by_tree_getDP(g2, 0);
		//dump(dp);

		res += dp[0].s01;

		repe(i, off[t]) col[i] = 0;
		//dump("col:", col);
	}

	res *= 2;

	return res;
}


//【DSU on Tree】O(n log n β + Q)
/*
* 根を rt とする木 g について,各頂点を根とする部分木に対するクエリを一括で処理する.
*
* insert(int s) : O(β)
*	部分木に頂点 s を追加し,データ構造を更新する.
*
* erase(int s) : O(β)
*	部分木から頂点 s を削除し,データ構造を更新する.
*
* get_sol(int s) : 計 O(Q)
*	部分木 s に対し,データ構造を参照して解を求める.
*/
template <class F_INS, class F_ERS, class F_SOL>
void dsu_on_tree(const Graph& g, int rt, const F_INS& insert, const F_ERS& erase, const F_SOL& get_sol) {
	// 参考 : https://nyaannyaan.github.io/library/tree/dsu-on-tree.hpp.html

	int n = sz(g);

	// hc[s] : 頂点 s の重さ最大の子
	vi hc(n, -1);

	// 各頂点の重さ最大の子を求める.
	function<int(int, int)> dfs_wgt = [&](int s, int p) {
		int ws = 0; int wt_max = -1;
		repe(t, g[s]) {
			if (t == p) continue;
			int wt = dfs_wgt(t, s);
			if (chmax(wt_max, wt)) hc[s] = t;
			ws += wt + 1;
		}
		return ws;
	};
	dfs_wgt(rt, -1);

	// 部分木 s 内の頂点を全て追加する.
	function<void(int, int)> dfs_insert = [&](int s, int p) {
		insert(s);
		repe(t, g[s]) {
			if (t == p) continue;
			dfs_insert(t, s);
		}
	};

	// 部分木 s 内の頂点を全て削除する.
	function<void(int, int)> dfs_erase = [&](int s, int p) {
		erase(s);
		repe(t, g[s]) {
			if (t == p) continue;
			dfs_erase(t, s);
		}
	};

	// 部分木 s 内の頂点を全て追加し,部分木 s に対するクエリに答える.
	// 必ず頂点集合が空の状態で呼ばれ,keep = false なら頂点集合を空に戻して関数を抜ける.
	function<void(int, int, bool)> dfs = [&](int s, int p, bool keep) {
		// light edge の先の部分木全てについての計算を行う.
		// 計算後は頂点集合は,空である.
		repe(t, g[s]) {
			if (t == p || t == hc[s]) continue;
			dfs(t, s, false);
		}

		// heavy edge の先の部分木についての計算を行う.
		// 計算後の頂点集合は,部分木 hc[s] 内の頂点全てである.
		if (hc[s] != -1) dfs(hc[s], s, true);

		// light edge の先の頂点全てと s 自身を追加する.
		// 計算後の頂点集合は,部分木 s 内の頂点全てである.
		repe(t, g[s]) {
			if (t == p || t == hc[s]) continue;
			dfs_insert(t, s);
		}
		insert(s);

		// 部分木 s に対するクエリに答える.
		get_sol(s);

		// keep フラグが false なら部分木 s 内の頂点を全て削除し,頂点集合を空にする.
		if (!keep) dfs_erase(s, p);
	};
	dfs(rt, -1, true);

	/* 雛形
	// freq[c] : 色 c の頂点の個数
	vi freq(n + 1);
	int freq_max = 0;

	// sum[f] : f 個ある色の色番号の和
	vl sum(n + 1);
	sum[0] = (ll)n * (n + 1) / 2;

	auto insert = [&](int s) {
		int col = c[s];
		int f = freq[col], nf = f + 1;

		sum[f] -= col;
		sum[nf] += col;

		freq[col] = nf;
		chmax(freq_max, nf);
	};

	auto erase = [&](int s) {
		int col = c[s];
		int f = freq[col], nf = f - 1;

		sum[f] -= col;
		sum[nf] += col;

		freq[col] = nf;
		if (sum[freq_max] == 0) freq_max = nf;
	};

	vl res(n);
	auto get_sol = [&](int s) {
		res[s] = sum[freq_max];
	};

	dsu_on_tree(g, 0, insert, erase, get_sol);
	*/
}


//【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 を返す.
*/
ull ans = 0;
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;

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

			ans += (ull)(n - ws - 1) * (ull)(ws + 1);
			//dump("s:", s, "->", (ull)(n - ws - 1), (ull)(ws + 1));

			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 };
		st.resize(n);

		// トップダウンに二分木を構築する.
		// [l..r) : heavy path, light child 共にどの範囲を見ているか
		function<void(Node*, int, int)> dfs_btree = [&](Node* p, int l, int r) {
			// 仮ラベルが 'C'
			if (p->tp == 'C') {
				// ラベルが 'C'
				if (r - l >= 2) {
					int m = (l + r) / 2;

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

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

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

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

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

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

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

					if (r <= 1) {
						p->tp = 'f';
						p->f = get_fnc(p->id);
						st[p->id] = p;
					}
					else {
						p->tp = 'C';
						dfs_btree(p, l, r);
					}
				}
			}
		};
		dfs_btree(root, 0, sz(hp[rt]));
	}
	Static_top_tree() {}

	// 頂点 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);
	*/
};


// 手動で切り詰めてみたら 4 つも削れた.
using F2 = array<ull, 6>;
F2 get_fnc2(int s) {
	if (col[s] == 0) {
		return F2{ 1, 1, 1, 0, ~0ULL, 0 };
	}
	else {
		return F2{ 1, ~0ULL, ~0ULL, 0, 1, 0 };
	}
}
F2 rake2(const F2& f, const F2& g) {
	auto [f1, f24, f35, f68, f79, f10] = f;
	auto [g1, g24, g35, g68, g79, g10] = g;

	return F2{ f1, f24 + g24, f35 + g35, f68 - f1 * g24 - g35, f79 - g24, f10 + g10 - f35 * g24 - f24 * g35 };
}
F2 comp2(const F2& f, const F2& g) {
	auto [f1, f24, f35, f68, f79, f10] = f;
	auto [g1, g24, g35, g68, g79, g10] = g;

	return F2{ f1 + g1, f24 + g24, f35 + f1 * g24 + g35, f68 + f79 * g1 + g68, f79 + g79, f10 + g10 + f68 * g24 + f79 * g35 };
}


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

	int n;
	cin >> n;

	auto g = read_Graph(n);
	auto g2 = read_Graph(n);

	//auto res_TLE = TLE(n, g, g2);
	//dump("TLE:", res_TLE); dump("======");

	rep(i, n) col[i] = 0;
	Static_top_tree<F2, get_fnc2, rake2, comp2> STT(g2, 0);
	ans *= (ull)n;
	//dump(ans);
	//exit(0); // 267 ms
	
	// HLD でどうのこうのしていたが,DSU on Tree でよかった.
	ull res = 0;
	auto insert_vtx = [&](int s) {
		col[s] = 1;
		STT.set(s);
	};
	auto erase_vtx = [&](int s) {
		col[s] = 0;
		STT.set(s);
	};
	auto get_sol = [&](int s) {
		//dump(STT.get());
		res += STT.get()[5];
	}; 
	dsu_on_tree(g, 0, insert_vtx, erase_vtx, get_sol);

	//dump((int)(res + 100000) - 100000);
	//dump("CONST:", res_TLE - res);

	EXIT(ans + res); // 2361 ms !!!!!!!!!!!!!!
}
0