public void Solve() { int N = Reader.Int(), A = Reader.Int() - 1, B = Reader.Int() - 1; var E = new List <int> [2][]; for (int who = 0; who < 2; who++) { E[who] = new List <int> [N]; for (int i = 0; i < N; i++) { E[who][i] = new List <int>(); } for (int i = 0; i < N - 1; i++) { int a = Reader.Int() - 1, b = Reader.Int() - 1; E[who][a].Add(b); E[who][b].Add(a); } } var lca = new LowestCommonAncestor(B, E[1]); var seen = new bool[N]; var que = new Queue <int>(); que.Enqueue(A); int ans = lca.Depth(A) * 2; for (int steps = 1; que.Count > 0; steps++) { var nextQue = new Queue <int>(); while (que.Count > 0) { int at = que.Dequeue(); foreach (int next in E[0][at]) { if (!seen[next]) { if (lca.Dist(at, next) > 2) { Console.WriteLine(-1); return; } seen[next] = true; int nextDepth = lca.Depth(next); if (nextDepth >= steps) { ans = Math.Max(ans, nextDepth * 2); } if (nextDepth > steps) { nextQue.Enqueue(next); } } } } que = nextQue; } Console.WriteLine(ans); }