降维处理的过程参考了这篇博客:降维处理
kmp套的是模板
#include <iostream>
#include <cstring>
#include <cstdio>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 510;
const int maxl = 2010;
char s[maxn][maxl];
int nnext[maxl];
void kmp_pre(char x[], int m, int nnext[]) {
int i = 0, j = nnext[0] = -1;
while (i < m) {
while (j != -1 && x[i] != x[j])
j = nnext[j];
nnext[++i] = ++j;
}
}
int KMP_Count(char x[], int m, char y[], int n) {//x是短的 y是长的
int i = 0, j = 0, ans = 0;
kmp_pre(x, m, nnext);
while (i < n) {
while (j != -1 && y[i] != x[j])
j = nnext[j];
i++; j++;
if (j >= m) {
ans++;
j = nnext[j];
}
}
return ans;//返回模式串的个数
}
bool match(char* x, char* y) {
int n = strlen(x), m = strlen(y);
if (KMP_Count(x, n, y, m) == 0)
return false;
return true;
}
int main(void) {
ios::sync_with_stdio(false);
int T, kase = 1, n;
cin >> T;
while (T--) {
cout << "Case #" << kase++ << ": ";
cin >> n;
for (int i = 1; i <= n; i++)
cin >> s[i];
int l = 1, ans = -1;
for (int r = 2; r <= n; r++) {
while (l < r) {
if (match(s[l], s[r]))
l++;
else {
ans = r;
break;
}
}
}
cout << ans << endl;
}
return 0;
}