/** * author: ivanzuki * created: Wed May 12 2021 **/ #include using namespace std; const int inf = (int) 1e9; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector> 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 deg(n); for (int i = 0; i < n - 1; i++) { int x, y; cin >> x >> y; --x; --y; ++deg[x]; ++deg[y]; } vector>> dp(n, vector>(4, vector(2, inf))); function 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> new_dp(4, vector(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; }