/* Problem URL: https://cses.fi/problemset/task/2101/ */ #include #include using namespace std; #define V vector #define rmin(a, b) a = min(a, b) #define rmax(a, b) a = max(a, b) #define rep(i, lim) for (size_t i = 0; i < (lim); i++) #define nrep(i, s, lim) for (size_t i = s; i < (lim); i++) #define repv(i, v) for (auto &i : (v)) #define fillv(v) for (auto &itr_ : (v)) { cin >> itr_; } #define sortv(v) sort(v.begin(), v.end()) #define all(v) (v).begin(), (v).end() using vi = vector; using vvi = vector; using vvvi = vector; using vvvvi = vector; using ll = long long; using vl = vector; using vvl = vector; using vvvl = vector; using vvvvl = vector; template auto operator<<(ostream &os, const vector &vec)->ostream& { os << vec[0]; for (size_t i = 1; i < vec.size(); i++) { os << ' ' << vec[i]; } os << '\n'; return os; } template auto operator>>(istream &is, vector &vec)->istream& { for (auto &i : vec) { is >> i; } return is; } template auto operator<<(ostream &os, const vector> &vec)->ostream& { for (auto &i : vec) { os << i[0]; for (size_t j = 1; j < i.size(); j++) { os << ' ' << i[j]; } os << '\n'; } return os; } template auto operator>>(istream &is, vector> &vec)->istream& { for (auto &i : vec) { for (auto &j : i) { is >> j; } } return is; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m, q; cin >> n >> m >> q; V> edges; rep(i, m) { int a, b; cin >> a >> b; a--, b--; edges.emplace_back(i, a, b); } vi dsu(n); rep(i, n) { dsu[i] = i; } function find_p = [&](int i){ if (dsu[i] == i) { return i; } return dsu[i] = find_p(dsu[i]); }; auto make_pair = [&](int a, int b) { a = find_p(a); b = find_p(b); if (a == b) { return false; } dsu[b] = a; return true; }; V>> graph(n); for (auto [i, a, b] : edges) { if (make_pair(a, b)) { graph[a].emplace_back(b, i + 1); graph[b].emplace_back(a, i + 1); } } vvi par(n, vi(20, 0)); vvi maximus(n, vi(20, 0)); vi depth(n, 0); function dfs = [&](int i, int p, int big){ par[i][0] = p; maximus[i][0] = big; depth[i] = depth[p] + 1; nrep(j, 1, 20) { par[i][j] = par[par[i][j - 1]][j - 1]; maximus[i][j] = max(maximus[i][j - 1], maximus[par[i][j - 1]][j - 1]); } for (auto [u, v] : graph[i]) { if (u == p) { continue; } dfs(u, i, v); } }; auto lca = [&](int a, int b){ if (depth[a] > depth[b]) { swap(a, b); } int ans = 0; int diff = depth[b] - depth[a]; for (int i = 19; i >= 0; i--) { if (diff & (1 << i)) { rmax(ans, maximus[b][i]); b = par[b][i]; } } if (a == b) { return ans; } for (int i = 19; i >= 0; i--) { if (par[a][i] != par[b][i]) { rmax(ans, maximus[a][i]); rmax(ans, maximus[b][i]); a = par[a][i]; b = par[b][i]; } } return max({ans, maximus[a][0], maximus[b][0]}); }; rep(i, n) { if (dsu[i] == i) { fill(all(par[i]), i); dfs(i, i, 0); } } while (q--) { int a, b; cin >> a >> b; a--, b--; if (find_p(a) != find_p(b)) { cout << "-1\n"; continue; } cout << lca(a, b) << '\n'; } }