#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e4;
int n, q, a[N], seg[N << 2];
char z[31], s[N][31];
unordered_map<ll, int> idx;
int calc(char *s) {
int n = strlen(s), ret = 0;
bool ok1, ok2;
for (int i = 0; i < n; ++i) {
ok1 = ok2 = true;
for (int j = 0;; ++j) {
if (i + j < n && i - j >= 0 && s[i + j] == s[i - j] && ok1)
++ret;
else
ok1 = false;
if (i + j + 1 < n && i - j >= 0 && s[i + j + 1] == s[i - j] && ok2)
++ret;
else
ok2 = false;
if (!ok1 && !ok2)
break;
}
}
return ret;
}
inline ll getHash(char *s) {
ll res = 0;
for (int i = 0; s[i]; ++i)
res = res * 4 + (s[i] - 'a' + 1);
return res;
}
void build(int index, int l, int r) {
if (l == r) {
seg[index] = l;
return;
}
int mid = (l + r) >> 1;
build(index << 1, l, mid);
build((index << 1) + 1, mid + 1, r);
seg[index] = a[seg[index << 1]] >= a[seg[(index << 1) + 1]] ? seg[index << 1] : seg[(index << 1) + 1];
}
int get(int index, int r, int l, int s, int e) {
if (l < s || r > e)
return -1;
if (s <= r && l <= e)
return seg[index];
int mid = (r + l) >> 1;
int c1 = get(index << 1, r, mid, s, e);
int c2 = get((index << 1) + 1, mid + 1, l, s, e);
if (c1 == -1)
return c2;
if (c2 == -1)
return c1;
return a[c1] >= a[c2] ? c1 : c2;
}
int main(int argc, char **argv) {
int t;
scanf("%d", &t);
while (t-- != 0) {
scanf("%d%d", &n, &q);
for (int i = 0; i < n; ++i)
scanf("%s", s[i]);
idx.clear();
for (int i = 0; i < n; ++i) {
a[i] = calc(s[i]);
idx[getHash(s[i])] = i;
}
build(1, 0, n - 1);
while (q-- != 0) {
scanf("%s", z);
ll l = idx[getHash(z)];
scanf("%s", z);
ll r = idx[getHash(z)];
if (r < l)
swap(l, r);
printf("%d\n", get(1, 0, n - 1, l, r) + 1);
}
}
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBz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