思路:
的解释在这里,有人证明了那么就很好计算了
之前对KMP了解不是很深啊,就很容易做错,特别是对fail的理解
代码:
#include#include const int N = 1000000+5;const int INF = 0x3f3f3f3f;using namespace std;int fail[N];char p[N],t[N];void getFail(){ fail[0] = -1; int j = 0,k = -1; int len = strlen(p); while(j <= len){ //给等号 if(k == -1 || p[j] == p[k]){ if(p[++j] == p[++k]) fail[j] = fail[k]; else fail[j] = k; } else{ k = fail[k]; } }}int KMP(){ int num = 0; getFail(); int i = 0,j = 0; int lent = strlen(t),lenp = strlen(p); while(i < lent){ if(j == -1 || t[i] == p[j]){ i++; j++; if(j == lenp) num++; } else{ j = fail[j]; } } return num;}int main(){ int T; scanf("%d",&T); while(T--){ scanf("%s",p); getFail(); int len = strlen(p); int c = len - fail[len]; //最小循环节 if(len % c == 0){ if(len == c) printf("%d\n",c); else printf("0\n"); } else{ printf("%d\n",c - len%c); } } return 0;}