import std.conv, std.functional, std.range, std.stdio, std.string; import std.algorithm, std.array, std.bigint, std.complex, std.container, std.math, std.numeric, std.regex, std.typecons; import core.bitop; class EOFException : Throwable { this() { super("EOF"); } } string[] tokens; string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; } int readInt() { return readToken.to!int; } long readLong() { return readToken.to!long; } real readReal() { return readToken.to!real; } bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } } bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } } int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; } int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); } int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); } enum INF = 10^^9; int N; int[] A, B; int[] C, D; int[][] G; int[] black; int[][][] dp; void dfs(int u, int p) { foreach (v; G[u]) { if (v != p) { dfs(v, u); } } auto crt = new int[][](2, 3); foreach (s; 0 .. 2) foreach (t; 0 .. 3) { crt[s][t] = INF; } crt[0][0] = 0; foreach (v; G[u]) { if (v != p) { auto nxt = new int[][](2, 3); foreach (s; 0 .. 2) foreach (t; 0 .. 3) { nxt[s][t] = INF; } foreach (s; 0 .. 2) foreach (t; 0 .. 3) { if (crt[s][t] < INF) { foreach (ss; 0 .. 2) foreach (tt; 0 .. 3) { if (t + tt < 3) { chmin(nxt[s ^ ss][t + tt], crt[s][t] + ss + dp[v][ss][tt]); } } } } crt = nxt; } } if (black[u]) { foreach (s; 0 .. 2) foreach (t; 0 .. 3) { chmin(dp[u][s ^ 1][t], crt[s][t]); if (t + 1 < 3) { chmin(dp[u][s][t + 1], crt[s][t]); } } } else { dp[u] = crt; } } void main() { try { for (; ; ) { N = readInt(); A = new int[N - 1]; B = new int[N - 1]; foreach (i; 0 .. N - 1) { A[i] = readInt() - 1; B[i] = readInt() - 1; } C = new int[N - 1]; D = new int[N - 1]; foreach (i; 0 .. N - 1) { C[i] = readInt() - 1; D[i] = readInt() - 1; } G = new int[][N]; foreach (i; 0 .. N - 1) { G[A[i]] ~= B[i]; G[B[i]] ~= A[i]; } black = new int[N]; foreach (i; 0 .. N - 1) { black[C[i]] ^= 1; black[D[i]] ^= 1; } dp = new int[][][](N, 2, 3); foreach (u; 0 .. N) { foreach (s; 0 .. 2) foreach (t; 0 .. 3) { dp[u][s][t] = INF; } } dfs(0, -1); int ans = dp[0][0][2]; ans += N - 1; writeln(ans); } } catch (EOFException e) { } }