結果

問題 No.3309 Aging Railway
コンテスト
ユーザー cho435
提出日時 2025-10-24 22:21:40
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 2,162 ms / 3,000 ms
コード長 1,530 bytes
コンパイル時間 4,499 ms
コンパイル使用メモリ 267,768 KB
実行使用メモリ 35,200 KB
最終ジャッジ日時 2025-10-24 22:22:20
合計ジャッジ時間 28,951 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 20
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#include <atcoder/all>
using namespace std;
using ll = long long;
#define rep(i, s, t) for (ll i = s; i < (ll)(t); i++)
#define all(x) begin(x), end(x)

template <class T> bool chmin(T& x, T y) {
	return x > y ? (x = y, true) : false;
}
template <class T> bool chmax(T& x, T y) {
	return x < y ? (x = y, true) : false;
}

struct io_setup {
	io_setup() {
		ios::sync_with_stdio(false);
		cin.tie(nullptr);
		cout << fixed << setprecision(15);
	}
} io_setup;

void solve() {
	int n, m;
	cin >> n >> m;
	vector<array<int, 2>> vp(n - 1);
	for (auto& [u, v] : vp) cin >> u >> v, u--, v--;
	map<pair<int, int>, int> mp;
	rep(i, 0, m) {
		int u, v;
		cin >> u >> v;
		u--, v--;
		mp[{u, v}]++;
	}
	atcoder::dsu uf(n);
	vector<vector<int>> vv(n);
	rep(i, 0, n) vv[i] = {(int)i};
	vector<int> ans = {0};
	int nw = 0;
	while (!vp.empty()) {
		auto [u, v] = vp.back();
		vp.pop_back();
		if (uf.same(u, v)) {
			ans.push_back(nw);
			continue;
		}
		u = uf.leader(u), v = uf.leader(v);
		for (int x : vv[u]) {
			for (int y : vv[v]) {
				auto itr = mp.find(minmax(x, y));
				if (itr != mp.end()) {
					nw += itr->second;
					mp.erase(itr);
				}
			}
		}
		{
			int w = uf.merge(u, v);
			v = u ^ v ^ w;
			u = w;
		}
		if (vv[u].size() < vv[v].size()) swap(vv[u], vv[v]);
		vv[u].insert(vv[u].end(), vv[v].begin(), vv[v].end());
		ans.push_back(nw);
	}
	ans.pop_back();
	while (!ans.empty()) {
		cout << ans.back() << '\n';
		ans.pop_back();
	}
}

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