結果
問題 |
No.912 赤黒木
|
ユーザー |
![]() |
提出日時 | 2019-10-17 15:15:51 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 935 ms / 3,000 ms |
コード長 | 1,585 bytes |
コンパイル時間 | 2,636 ms |
コンパイル使用メモリ | 198,060 KB |
最終ジャッジ日時 | 2025-01-07 22:11:30 |
ジャッジサーバーID (参考情報) |
judge2 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 30 |
ソースコード
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; int N; vector<int> G[200000]; int deg[200000]; int dp[200000][3]; void calc(int v, int p){ for(auto to : G[v]){ if(to == p) continue; calc(to, v); deg[v] += deg[to]; int nxt[3] = {INF, INF, INF}; for(int i = 0; i < 3; i++){ for(int j = 0; i + j < 3; j++){ nxt[i + j] = min(nxt[i + j], dp[v][i] + dp[to][j] + !(deg[to] % 2 == j % 2)); } } swap(dp[v], nxt); } } struct UF{ vector<int> par, sz; UF(){} UF(int n):par(n), sz(n, 1){ iota(par.begin(), par.end(), 0); } int find(int x){ if(x == par[x]) return x; return par[x] = find(par[x]); } void unite(int x, int y){ x = find(x); y = find(y); if(x == y) return; if(sz[x] < sz[y]) swap(x, y); sz[x] += sz[y]; par[y] = x; } bool same(int x, int y){ return find(x) == find(y); } }; int main(){ cin >> N; assert(2 <= N && N <= 200000); UF ufr(N), ufb(N); for(int i = 0; i < N - 1; i++){ int A, B; cin >> A >> B; A--; B--; G[A].push_back(B); G[B].push_back(A); ufr.unite(A, B); } assert(ufr.sz[ufr.find(0)] == N); for(int i = 0; i < N - 1; i++){ int C, D; cin >> C >> D; C--; D--; deg[C]++; deg[D]++; ufb.unite(C, D); } assert(ufb.sz[ufb.find(0)] == N); calc(0, -1); cout << min(dp[0][0], dp[0][2]) + N - 1 << endl; }