#include #include #include #include #include #include #include #include using namespace std; int N, K; // K <= 300 int A[10002], B[10002], niv[100002]; bool S[10002], Sn[302]; int D[302][302], wh[302][2]; vector W[302]; vector V[10002]; void Dfs(int x) { S[x] = true; for (auto nod : V[x]) if (!S[nod]) { niv[nod] = niv[x] + 1; Dfs(nod); } } bool match(int x) { if (Sn[x]) return false; Sn[x] = true; for (auto i : W[x]) if (wh[i][1] == 0 || match(wh[i][1])) { wh[x][0] = i; wh[i][1] = x; return true; } return false; } bool Test(int lim) { for (int i = 1; i <= K; ++i) W[i].clear(); for (int i = 1; i <= K; ++i) for (int j = 1; j <= K; ++j) if (D[i][j] <= lim) W[i].push_back(j); int rn = 0; memset(wh, 0, sizeof(wh)); bool change = true; while (change) { change = false; memset(Sn, 0, sizeof(Sn)); for (int i = 1; i <= K; ++i) if (wh[i][0] == 0 && match(i)) { ++rn; change = true; } } return (rn == K); } int main() { cin.sync_with_stdio(false); cin >> N >> K; for (int i = 1; i <= K; ++i) cin >> A[i]; for (int i = 1; i <= K; ++i) cin >> B[i]; for (int i = 1, nod1, nod2; i <= N - 1; ++i) { cin >> nod1 >> nod2; V[nod1].push_back(nod2); V[nod2].push_back(nod1); } for (int i = 1; i <= K; ++i) { memset(S, 0, sizeof(S)); niv[A[i]] = 0; Dfs(A[i]); for (int j = 1; j <= K; ++j) D[i][j] = niv[B[j]]; } int step = (1 << 16), result = -1; for (; step; step >>= 1) if (!Test(result + step)) result += step; ++result; cout << result << '\n'; }