voidsolve(){ int n, s1, s2; std::cin >> n >> s1 >> s2; -- s1, -- s2; std::vector g1(n, std::vector<int>(n)); std::vector g2(n, std::vector<int>(n)); std::vector<std::vector<int> > adj1(n); std::vector<std::vector<int> > adj2(n); int m1, m2; std::cin >> m1; for (int i = 0; i < m1; ++ i) { int u, v; std::cin >> u >> v; -- u, -- v; g1[u][v] = g1[v][u] = 1; adj1[u].push_back(v); adj1[v].push_back(u); }
std::cin >> m2; for (int i = 0; i < m2; ++ i) { int u, v; std::cin >> u >> v; -- u, -- v; g2[u][v] = g2[v][u] = 1; adj2[u].push_back(v); adj2[v].push_back(u); }
constint inf = 1e9; std::vector dist(n, std::vector<int>(n, inf)); std::vector vis(n, std::vector<int>(n)); using A = std::array<int, 3>; std::priority_queue<A, std::vector<A>, std::greater<A> > heap; dist[s1][s2] = 0; heap.push({0, s1, s2}); while (heap.size()) { auto [_, x, y] = heap.top(); heap.pop(); if (vis[x][y]) { continue; }
for (auto & i : adj1[x]) { for (auto & j : adj2[y]) { if (dist[i][j] > dist[x][y] + std::abs(i - j)) { dist[i][j] = dist[x][y] + std::abs(i - j); if (!vis[i][j]) { heap.push({dist[i][j], i, j}); } } } } }
int ans = inf; for (int i = 0; i < n; ++ i) { for (int j = 0; j < n; ++ j) { if (g1[i][j] && g2[i][j]) { ans = std::min(ans, dist[i][i]); } } }
if (ans == inf) { ans = -1; } std::cout << ans << endl; }