Code : Colored Portals
#include <bits/stdc++.h>
using namespace std;
const int inf = 1e8;
void solve() {
int n, q;
cin >> n >> q;
vector<int> a(n + 1, 0);
map<char, int> index;
index['R'] = 0, index['G'] = 1, index['B'] = 2, index['Y'] = 3;
for (int i = 1; i <= n; i++) {
int mask = 0;
string str;
cin >> str;
for (auto &ch : str) {
mask |= (1 << index[ch]);
}
a[i] = mask;
}
// ldp[i] is the closest node to the left with exactly one common bit.
vector<int> ldp(n + 1, -1);
map<int, int> last;
for (int i = 1; i <= n; i++) {
for (auto &[mask, ind] : last) {
if (__builtin_popcount(mask & a[i]) == 1) {
ldp[i] = max(ldp[i], ind);
}
}
last[a[i]] = i;
}
// rdp[i] is the closest node to the right with exactly one common bit.
vector<int> rdp(n + 1, inf);
last.clear();
for (int i = n; i >= 1; i--) {
for (auto &[mask, ind] : last) {
if (__builtin_popcount(mask & a[i]) == 1) {
rdp[i] = min(rdp[i], ind);
}
}
last[a[i]] = i;
}
while (q--) {
int x, y;
cin >> x >> y;
if (x > y) {
swap(x, y);
}
int dist = abs(x - y);
if ((a[x] & a[y]) == 0) {
int delta = inf;
if (ldp[x] != -1) {
delta = min(delta, 2 * (x - ldp[x]));
}
if (rdp[x] != inf) {
delta = min(delta, 2 * (max(0, rdp[x] - y)));
}
dist += delta;
}
if (dist >= inf) {
cout << -1 << "\n";
} else {
cout << dist << "\n";
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
solve();
}
}