# data[].attributes.body
hsg12_2023_v2_6

#include <bits/stdc++.h> using namespace std; const int N = 9e4 + 5; const int M = 1e3 + 5; const int inf = 0x3f3f3f3f; int a[N],b[N],dist[M][M]; vector<int>g[M]; void bfs(int s) { queue<int>q; dist[s][s] = 1; q.push(s); while (!q.empty()) { int u = q.front(); q.pop(); for (auto v: g[u]) if (dist[s][v] == inf) { dist[s][v] = dist[s][u] + 1; q.push(v); } } } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); freopen("friendship.inp","r",stdin); freopen("friendship.out","w",stdout); int n,s; cin >> n >> s; int maxi = 0; for (int i = 1; i <= n; i++) { cin >> a[i] >> b[i]; a[i] = a[i] * 2; b[i] = b[i] * 2 + 1; maxi = max({maxi,a[i],b[i]}); g[a[i]].push_back(b[i]); g[b[i]].push_back(a[i]); } for (int i = 1; i <= maxi; i++) { for (int j = 1; j <= maxi; j++) dist[i][j] = inf; bfs(i); } int q; cin >> q; while (q--) { int x,y; cin >> x >> y; int ans = min({dist[a[x]][a[y]],dist[a[x]][b[y]],dist[b[x]][a[y]],dist[b[x]][b[y]]}); if (ans == inf) ans = -1; cout << ans << "\n"; } }

# data[].attributes.attachment_link.readable_text
#include <bits/stdc++.h>
using namespace std;

const int N = 9e4 + 5;
const int M = 1e3 + 5;
const int inf = 0x3f3f3f3f;
int a[N],b[N],dist[M][M];
vector<int>g[M];

void bfs(int s) {
    queue<int>q;
    dist[s][s] = 1;
    q.push(s);
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (auto v: g[u]) 
            if (dist[s][v] == inf) {
                dist[s][v] = dist[s][u] + 1;
                q.push(v);
            }
    }
}

signed main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    freopen("friendship.inp","r",stdin);
    freopen("friendship.out","w",stdout);
    int n,s;
    cin >> n >> s;
    int maxi = 0;
    for (int i = 1; i <= n; i++) {
        cin >> a[i] >> b[i];
        a[i] = a[i] * 2;
        b[i] = b[i] * 2 + 1;
        maxi = max({maxi,a[i],b[i]});
        g[a[i]].push_back(b[i]);
        g[b[i]].push_back(a[i]);
    }
    for (int i = 1; i <= maxi; i++) {
        for (int j = 1; j <= maxi; j++) dist[i][j] = inf;
        bfs(i);
    }
    int q;
    cin >> q;
    while (q--) {
        int x,y;
        cin >> x >> y;
        int ans = min({dist[a[x]][a[y]],dist[a[x]][b[y]],dist[b[x]][a[y]],dist[b[x]][b[y]]});
        if (ans == inf) ans = -1;
        cout << ans << "\n";
    }
}