for (int i = 1; i <= n; i++) { if (i == 1) pre[i].fill(0); else pre[i] = pre[i - 1]; pre[i][id(c[i][0], c[i][1])] = i; } for (int i = n; i >= 1; i--) { if (i == n) nxt[i].fill(n + 1); else nxt[i] = nxt[i + 1]; nxt[i][id(c[i][0], c[i][1])] = i; }
for (int i = 0; i < q; i++) { int x = read(), y = read(); int ans = 1e9; if (x > y) swap(x, y); for (auto a : c[x]) { for (auto b : c[y]) { if (a == b) ans = y - x; else { int w = id(a, b); for (auto z : {nxt[x][w], pre[y][w]}) { if (1 <= z and z <= n) { ans = min(ans, abs(x - z) + abs(y - z)); } } } } }