#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
string s, t;
int nxt[maxn];
bool mp[1005][1005];
string str[maxn];
void get_next(string s){
int n = s.size() - 1;
nxt[1] = 0;
int idx = 0, i = 2;
while(i <= n){
if(s[i] == s[idx + 1]){
idx++;
nxt[i] = idx;
i++;
}
else{
if(idx == 0){
nxt[i] = 0;
i++;
}
else idx = nxt[idx];
}
}
}
int kmp(string s, string t){
int n = s.size() - 1, m = t.size() - 1;
int i = 1, j = 1;
while(i <= n && j <= m){
if(s[i] == t[j]){
i++;
j++;
}
else{
if(j == 1) i++;
else j = nxt[j - 1] + 1;
}
}
if(j > m) return i - j + 1;
return 0;
}
void solve(){
int n, m, i, j;
cin >> n >> m;
if(n * n <= 100000){//根号分治,字符串个数较少时,任意两个都让其中一个字符串复制一次,然后kmp跑一遍,用数组记录这两个是否匹配
for(i = 1; i <= n; i++){//复杂度:O(n*n*m)
for(j = 1; j <= n; j++){
if(i == j) mp[i][j] = 1;
else mp[i][j] = 0;
}
cin >> str[i];
//cout << str[i] << '\n';
}
for(i = 1; i < n; i++){
t = str[i];
t = " " + t;//求nxt数组和kmp都要右移一次,因为下标从1开始
get_next(t);
for(j = i + 1; j <= n; j++){
s = str[j];
s += s;
s = ' ' + s;
if(kmp(s, t)) mp[i][j] = mp[j][i] = 1;
}
}
int q;
cin >> q;
while(q--){
int x, y;
cin >> x >> y;
if(mp[x][y] == 1) cout << "Yes\n";
else cout << "No\n";
}
}
else{//字符串个数较多,长度较短时,对于每一个询问,直接让其中一个字符串复制一次,然后kmp跑一遍。
//复杂度O(q*m))
for(i = 1; i <= n; i++){
cin >> str[i];
}
int q;
cin >> q;
while(q--){
int x, y;
cin >> x >> y;
s = ' ' + str[x] + str[x], t = ' ' + str[y];
get_next(t);
if(kmp(s, t)) cout << "Yes\n";
else cout << "No\n";
}
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int T;
cin >> T;
while(T--){
solve();
}
return 0;
}
法二:字符串的最小表示法