結果

問題 No.763 Noelちゃんと木遊び
ユーザー ecottea
提出日時 2025-09-26 02:42:55
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 44 ms / 2,000 ms
コード長 17,934 bytes
コンパイル時間 5,720 ms
コンパイル使用メモリ 300,512 KB
実行使用メモリ 22,016 KB
最終ジャッジ日時 2025-09-26 02:43:03
合計ジャッジ時間 8,403 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 22
権限があれば一括ダウンロードができます

ソースコード

diff #

#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


// 頂点 0 を virtual な根とする木 par に対する愚直解を計算する.
// virtual な根を考えたくなければ,頂点 0 と接続辺を無視して森として扱えばいい.
ll naive(const vi& par) {
	int n = sz(par) + 1;

	int res = 0;

	repb(set, n) {
		// virtual な根は選択不可とする.
		if (getb(set, 0)) continue;

		bool ok = true;

		repi(i, 1, n - 1) {
			if (getb(set, i) && getb(set, par[i - 1])) {
				ok = false;
				break;
			}
		}

		if (ok) chmax(res, popcount(set));
	}

	return res;
}


//【グラフの入力】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;
}


// (グラフ, 根) を naive() への入力形式に直す.
vi inputform(const Graph& g, int r) {
	int n = sz(g);

	vi par(n);
	function<void(int, int)> dfs = [&](int s, int p) {
		par[s] = { p + 1 };

		repe(t, g[s]) {
			if (t == p) continue;
			dfs(t, s);
		}
	};
	dfs(r, -1);

	return par;
}


//【根付き木の同型類】O(n log n)
/*
* r を根とする根付き木 g について,各部分木の同型類を分類したリストを返す.
*/
vi rooted_tree_classification(const Graph& g, int r) {
	// 参考 : https://chocobaby-aporo.hatenablog.com/entry/2017/12/05/233027
	// verify : https://judge.yosupo.jp/problem/rooted_tree_isomorphism_classification

	int n = sz(g);

	static map<vi, int> to_id;
	vi id(n);

	function<int(int s, int p)> dfs = [&](int s, int p) {
		vi ch;
		repe(t, g[s]) {
			if (t == p) continue;
			ch.push_back(dfs(t, s));
		}
		sort(all(ch));

		if (to_id.count(ch)) id[s] = to_id[ch];
		else id[s] = to_id[ch] = sz(to_id);

		return id[s];
	};
	dfs(r, -1);

	return id;
}


//【木のランダム生成】O(?)
/*
* n 頂点のランダムな木を返す.
*/
Graph create_random_tree(int n) {
	Graph g(n);

	static mt19937_64 mt; static bool first_call = true;
	if (first_call) {
		mt = mt19937_64((int)time(NULL));
		first_call = false;
	}

	uniform_int_distribution<int> rnd(0, n - 1);

	dsu d(n);
	while (d.size(0) < n) {
		int u = rnd(mt), v = rnd(mt);
		if (d.same(u, v)) continue;

		g[u].emplace_back(v);
		g[v].emplace_back(u);
		d.merge(u, v);
	}

	return g;
}


//【木の出力】O(n + m)
/*
* 木を【木の入力】で受け取る入力と同じ形式で出力する.
*
* directed : 有向木か(省略すれば false)
* zero_indexed : 入力が 0-indexed か(省略すれば false)
*/
void write_Tree(const Graph& g, bool directed = false, bool zero_indexed = false) {
	int n = sz(g);

	cout << n << endl;
	rep(s, n) repe(t, g[s]) {
		if (!directed && s > t) continue;

		int u = s + (!zero_indexed), v = t + (!zero_indexed);
		cout << u << " " << v << " " << endl;
	}
}


// 遷移行列の係数を計算し,埋め込み用のコードを出力する.
// 待てない場合は lv_max や LT_max を指定する.
tuple<vvl, vvvl, vl> embed_coefs(int lv_min = 0, int lv_max = INF, int LT_max = INF,
	vvi treesB_ini = { {} }) {
	vvi trees{ {0} };
	int idx = 0;
	int ID = rooted_tree_classification(Graph{ {1},{0} }, 0)[0];

	int PDIM = -1;

	repi(lv, 2, INF) {
		dump("----------- lv:", lv, "--------------");
		
		// 上用の木と下用の木に整形する.
		vvi treesT, treesB;
		treesT.push_back(vi{0});
		repe(treeB, treesB_ini) treesB.push_back(treeB);
		rep(i, idx) repi(p, 0, sz(trees[i])) {
			treesT.push_back(trees[i]);
			treesT.back().push_back(p);
		}
		repe(tree, trees) treesB.push_back(tree);
		
		int LT = min(sz(treesT), LT_max); int LB = sz(treesB);
		dump("LT:", LT, "LB:", LB);
		//dump(treesT); dump(treesB);

		// (i,j) 成分が naive(trees[i] join trees[j]) であるような行列 mat を得る.
		vvl mat(LT, vl(LB));
		rep(i, LT) rep(j, LB) {
			vi tree(treesT[i]);
			int p0 = tree.back();
			tree.pop_back();

			int offset = sz(tree);
			repe(p, treesB[j]) {
				int np = (p == 0 ? p0 : p + offset);
				tree.push_back(np);
			}

			mat[i][j] = naive(tree);
		}
		//dump("mat:"); dumpel(mat);

		// mat から max-plus 線形独立な行を抜き出す.
		vi js; int DIM = 0;
		rep(j, LB) {
			vl coef(DIM, INFL);
			rep(j2, DIM) rep(i, LT) {
				if (mat[i][js[j2]] == -INFL) continue;
				chmin(coef[j2], mat[i][j] - mat[i][js[j2]]);
			}

			bool ok = true;
			rep(i, LT) {
				ll val = -INFL;
				rep(j2, DIM) {
					ll nval = mat[i][js[j2]] + coef[j2];
					if (nval < -INFL / 2) continue;
					chmax(val, nval);
				}

				if (val != mat[i][j]) {
					ok = false;
					break;
				}
			}

			if (!ok) {
				js.push_back(j);
				DIM++;
			}
		}
		dump("js[0.." + to_string(DIM) + "):"); dump(js);		
		vvi treesB_sub; repe(j, js) treesB_sub.push_back(treesB[j]); dump_math(treesB_sub);

		// rank の更新がなかったら必要な情報は揃ったとみなして打ち切る.
		if (lv == lv_max || (lv >= lv_min && DIM == PDIM)) { // たまにミスる
			// apply の表現行列を得る.
			vvl matA(DIM, vl(DIM, INFL));
			rep(j, DIM) {
				vl vec(LT);
				rep(i, LT) {
					vi tree(treesT[i]);

					int offset = sz(tree);
					repe(p, treesB[js[j]]) {
						int np = p + offset;
						tree.push_back(np);
					}

					vec[i] = naive(tree);
				}

				rep(k, DIM) rep(i, LT) {
					if (mat[i][js[k]] == -INFL) continue;
					chmin(matA[j][k], vec[i] - mat[i][js[k]]);
				}

				vl vec2(LT);
				rep(i, LT) {
					vec2[i] = -INFL;
					rep(k, DIM) {
						ll nval = mat[i][js[k]] + matA[j][k];
						if (nval < -INFL / 2) continue;
						chmax(vec2[i], nval);
					}
				}
				if (vec2 != vec) {
					dump("ERROR!");
					dump("j:", j, "treesB[js[j]]:", treesB[js[j]]);
					dump("vec:"); dump(vec);
					dump("vec2:"); dump(vec2);
					exit(-1);
				}

				rep(k_el, DIM) {
					vl vec_el(LT, -INFL);
					rep(k, DIM) {
						if (k == k_el) continue;
						rep(i, LT) {
							auto nval = mat[i][js[k]] + matA[j][k];
							if (nval < -INFL / 2) continue;
							chmax(vec_el[i], nval);
						}
					}
					if (vec_el == vec) matA[j][k_el] = -INFL;
				}
			}

			// merge の表現テンソルを得る.
			vvvl tsrM(DIM, vvl(DIM, vl(DIM, INFL)));
			rep(j1, DIM) rep(j2, DIM) {
				if (j1 > j2) {
					rep(k, DIM) {
						tsrM[j1][j2][k] = tsrM[j2][j1][k];
					}
				}
				else {
					vl vec(LT);
					rep(i, LT) {
						vi tree(treesT[i]);
						int p0 = tree.back();
						tree.pop_back();

						int offset = sz(tree);
						repe(p, treesB[js[j1]]) {
							int np = (p == 0 ? p0 : p + offset);
							tree.push_back(np);
						}

						offset = sz(tree);
						repe(p, treesB[js[j2]]) {
							int np = (p == 0 ? p0 : p + offset);
							tree.push_back(np);
						}

						vec[i] = naive(tree);
					}

					rep(k, DIM) rep(i, LT) {
						if (mat[i][js[k]] == -INFL) continue;
						chmin(tsrM[j1][j2][k], vec[i] - mat[i][js[k]]);
					}

					vl vec2(LT);
					rep(i, LT) {
						vec2[i] = -INFL;
						rep(k, DIM) {
							ll nval = mat[i][js[k]] + tsrM[j1][j2][k];
							if (nval < -INFL / 2) continue;
							chmax(vec2[i], nval);
						}
					}
					if (vec2 != vec) {
						dump("ERROR!");
						dump("j1:", j1, "treesB[js[j1]]:", treesB[js[j1]]);
						dump("j2:", j2, "treesB[js[j2]]:", treesB[js[j2]]);
						dump("vec:"); dump(vec);
						dump("vec2:"); dump(vec2);
						exit(-1);
					}

					rep(k_el, DIM) {
						vl vec_el(LT, -INFL);
						rep(k, DIM) {
							if (k == k_el) continue;
							rep(i, LT) {
								auto nval = mat[i][js[k]] + tsrM[j1][j2][k];
								if (nval < -INFL / 2) continue;
								chmax(vec_el[i], nval);
							}
						}
						if (vec_el == vec) tsrM[j1][j2][k_el] = -INFL;
					}
				}
			}
			
			// 根を閉じるためのベクトルを得る.
			vl vecQ(DIM);
			rep(j, DIM) vecQ[j] = mat[0][js[j]];

			// 埋め込み用の文字列を出力する.
			string eb = "\n";
			eb += "constexpr int DIM = ";
			eb += to_string(DIM);
			eb += ";\n";
			eb += "VTYPE matA[DIM][DIM] = {";
			rep(j, DIM) {
				eb += "{";
				rep(k, DIM) eb += to_string(matA[j][k]) + ",";
				eb.pop_back();
				eb += "},";
			}
			eb.pop_back();
			eb += "};\n";
			eb += "VTYPE tsrM[DIM][DIM][DIM] = {";
			rep(j1, DIM) {
				eb += "{";
				rep(j2, DIM) {
					eb += "{";
					rep(k, DIM) eb += to_string(tsrM[j1][j2][k]) + ",";
					eb.pop_back();
					eb += "},";
				}
				eb.pop_back();
				eb += "},";
			}
			eb.pop_back();
			eb += "};\n";
			eb += "VTYPE vecQ[DIM] = {";
			rep(j, DIM) eb += to_string(vecQ[j]) + ",";
			eb.pop_back();
			eb += "};\n";
			cout << eb;
			exit(0);

			return { matA, tsrM, vecQ };
		}

		// 基底ガチャ
		//mt19937_64 mt((int)time(NULL)); shuffle(trees.begin() + idx, trees.end(), mt);
		
		// 次に大きい木たちを trees に追加する.
		int nidx = sz(trees);
		repi(i, idx, nidx - 1) rep(p, lv) {
			trees.push_back(trees[i]);
			trees.back().push_back(p);

			Graph g(lv + 1);
			rep(j, lv) {
				g[j + 1].push_back(trees.back()[j]);
				g[trees.back()[j]].push_back(j + 1);
			}

			auto hash = rooted_tree_classification(g, 0);
			if (hash[0] <= ID) {
				trees.pop_back();
				continue;
			}
			ID = hash[0];
		}
		idx = nidx;

		PDIM = DIM;
	}

	return tuple<vvl, vvvl, vl>();
}


template <class VTYPE>
vector<VTYPE> solve(const Graph& g, int r) {
	// --------------- embed_coefs() からの出力を貼る ----------------
	constexpr int DIM = 2;
	VTYPE matA[DIM][DIM] = { {-4004004004,0},{1,-4004004004} };
	VTYPE tsrM[DIM][DIM][DIM] = { {{0,-4004004004},{-4004004004,0}},{{-4004004004,0},{-4004004004,1}} };
	VTYPE vecQ[DIM] = { 0,1 };
	// --------------------------------------------------------------


	// ここ以降は書き換えなくて良い.
	int n = sz(g);
	vector<array<VTYPE, DIM>> dp(n);
	rep(s, n) {
		dp[s].fill((VTYPE)(-INFL));
		dp[s][0] = 0;
	}

	auto apply = [&](const array<VTYPE, DIM>& x) {
		array<VTYPE, DIM> z;
		z.fill((VTYPE)(-INFL));

		rep(j, DIM) {
			rep(k, DIM) chmax(z[k], x[j] + matA[j][k]);
		}

		return z;
	};

	auto merge = [&](const array<VTYPE, DIM>& x, const array<VTYPE, DIM>& y) {
		array<VTYPE, DIM> z;
		z.fill((VTYPE)(-INFL));

		rep(j1, DIM) rep(j2, DIM) {
			rep(k, DIM) chmax(z[k], x[j1] + y[j2] + tsrM[j1][j2][k]);
		}

		return z;
	};

	function<void(int, int)> dfs = [&](int s, int p) {
		bool first_call = true;

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

			dfs(t, s);

			if (first_call) {
				dp[s] = dp[t];
			}
			else {
				dp[s] = merge(dp[s], dp[t]);
			}

			first_call = false;
		}

		dp[s] = apply(dp[s]);
	};
	dfs(r, -1);
	
	dump("dp:"); dumpel(dp);

	vector<VTYPE> res(n, (VTYPE)(-INFL));
	rep(s, n) {
		rep(j, DIM) chmax(res[s], vecQ[j] + dp[s][j]);
	}

	return res;
}


void bug_find() {
#ifdef _MSC_VER
	// 合わない入力例を見つける.

	mt19937_64 mt((int)time(NULL));
	uniform_int_distribution<ll> rnd(0LL, 1LL << 60);

	rep(hoge, 1000000) {
		//dump("==================================================================================");

		int n = rnd(mt) % 30 + 1;
		auto g = create_random_tree(n);

		auto res_naive = naive(inputform(g, 0));
		auto res_solve = solve<ll>(g, 0)[0];

		if (res_naive != res_solve) {
			cout << "----------error!----------" << endl;
			cout << "input:" << endl;
			write_Tree(g);
			cout << "results:" << endl;
			cout << res_naive << endl;
			cout << res_solve << endl;
			cout << "--------------------------" << endl;
			//exit(-1);
		}
	}

	mute_dump = false;
	exit(0);
#endif
}


int main() {
//	input_from_file("input.txt");
//	output_to_file("output.txt");
	
	//【方法】
	// 愚直を書いて集めたデータをもとに遷移テンソルを復元する.

	//【使い方】
	// 1. mint naive(親の列) を実装する.
	// 2. embed_coefs(); を実行する.
	// 3. 出力を solve() 内に貼る.
	// 4. auto dp = solve<答えの型>(グラフ, 根) で勝手に DP してくれる.

//	INFL = 999;
//	bug_find();

//	embed_coefs(0, INF, INF); 

	vvi treesB = { {}, { 0,1,2,3,4,5,6,7,8,9 } };
//	embed_coefs(0, INF, INF, treesB);

	int n;
	cin >> n;

	auto g = read_Graph(n);

	dump("naive:", naive(inputform(g, 0))); dump("======");

	auto dp = solve<ll>(g, 0);

	cout << dp[0] << "\n";
}
0