結果
| 問題 |
No.912 赤黒木
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2021-05-12 19:11:57 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 522 ms / 3,000 ms |
| コード長 | 3,096 bytes |
| コンパイル時間 | 2,438 ms |
| コンパイル使用メモリ | 206,408 KB |
| 最終ジャッジ日時 | 2025-01-21 10:16:57 |
|
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 |
| other | AC * 30 |
ソースコード
/**
* author: ivanzuki
* created: Wed May 12 2021
**/
#include <bits/stdc++.h>
using namespace std;
const int inf = (int) 1e9;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<vector<int>> g(n);
for (int i = 0; i < n - 1; i++) {
int x, y;
cin >> x >> y;
--x; --y;
g[x].push_back(y);
g[y].push_back(x);
}
vector<int> deg(n);
for (int i = 0; i < n - 1; i++) {
int x, y;
cin >> x >> y;
--x; --y;
++deg[x];
++deg[y];
}
vector<vector<vector<int>>> dp(n, vector<vector<int>>(4, vector<int>(2, inf)));
function<void(int, int)> DFS = [&](int v, int pv) {
dp[v][deg[v] % 2][deg[v] % 2] = 0;
for (int u : g[v]) {
if (u == pv) {
continue;
}
DFS(u, v);
// (# of odd-degree vertices, is v an odd-degree vertex?)
vector<vector<int>> new_dp(4, vector<int>(2, inf));
// add the (v, u) edge
for (int x = 0; x <= 3; x++) {
for (int y = 0; y < 2; y++) {
for (int z = 0; z <= 3; z++) {
for (int w = 0; w < 2; w++) {
{
// add the edge
int p = x + (y == 1 ? -1 : 1) + z + (w == 1 ? -1 : 1);
int q = 1 - y;
if ((p >= 0 && p <= 2) || (p == 3 && q == 1)) {
new_dp[p][q] = min(new_dp[p][q], 1 + dp[v][x][y] + dp[u][z][w]);
}
}
{
// do not add the edge
int p = x + z;
int q = y;
if ((p >= 0 && p <= 2) || (p == 3 && q == 1)) {
new_dp[p][q] = min(new_dp[p][q], dp[v][x][y] + dp[u][z][w]);
}
}
}
}
}
}
dp[v] = new_dp;
// new_dp[0][0] = min(new_dp[0][0], 1 + dp[v][1][1] + dp[u][1][1]);
// new_dp[1][0] = min(new_dp[1][0], 1 + dp[v][1][1] + dp[u][0][0]);
// new_dp[1][1] = min(new_dp[1][1], 1 + dp[v][0][0] + dp[u][1][1]);
// new_dp[2][0] = min(new_dp[2][0], 1 + dp[v][3][1] + dp[u][1][1]);
// new_dp[2][0] = min(new_dp[2][0], 1 + dp[v][1][1] + dp[u][1][0]);
// new_dp[2][0] = min(new_dp[2][0], 1 + dp[v][1][1] + dp[u][3][1]);
// new_dp[2][1] = min(new_dp[2][1], 1 + dp[v][1][0] + dp[u][3][1]);
// new_dp[2][1] = min(new_dp[2][1], 1 + dp[v][0][0] + dp[u][0][0]);
// new_dp[2][1] = min(new_dp[2][1], 1 + dp[v][0][0] + dp[u][3][1]);
// new_dp[2][1] = min(new_dp[2][1], 1 + dp[v][1][0] + dp[u][0][0]);
// new_dp[3][1] = min(new_dp[3][1], 1 + dp[v][2][0] + dp[u][1][1]);
// new_dp[3][1] = min(new_dp[3][1], 1 + dp[v][1][0] + dp[u][0][0]);
// new_dp[3][1] = min(new_dp[3][1], 1 + dp[v][1][0] + dp[u][2][1]);
// new_dp[3][1] = min(new_dp[3][1], 1 + dp[v][0][0] + dp[u][3][1]);
// new_dp[3][1] = min(new_dp[3][1], 1 + dp[v][0][0] + dp[u][1][0]);
// do not add the (v, u) edge
// new_dp[0][0] = min(new_dp[0][0],
}
};
DFS(0, -1);
int ans = n - 1 + min({dp[0][0][0], dp[0][2][0], dp[0][2][1]});
cout << ans << '\n';
return 0;
}