HDU 1358 Period(KMP求周期)

来源:互联网 发布:奥尼尔体测数据官网 编辑:程序博客网 时间:2024/05/17 09:36
/*题意:输入字符串长度N和字符串S,要求输出所有字符串S前k个字母组成的序列A为循环序列时,循环序列的个数Ak,k从小到大一次输出。KMP解决,可以将算法时间复杂度缩小为O(N),然后找规律即可。KMP算法可将字符串匹配算法时间复杂度从O(N*M)缩小到O(N+M)*/#include <cstdio>const int nMax = 1000007;char S[nMax];int next[nMax];int N;void getNext(){next[0]=-1;int i,j;for(i = 0, j = -1; i < N; ){if(j == -1 || S[i] == S[j]){++ i;++ j;next[i] = j;}elsej = next[j];}}int main(){//freopen("f://data.in","r",stdin);int cas = 1;while(scanf("%d", &N) && N){printf("Test case #%d\n", cas ++);scanf("%s",S);getNext();int ans=1;int i;for(i = 1; i < N; ++ i)if(S[i] == S[next[i]]){if(i == 1)printf("2 2\n");else{if((next[i] + 1) % (i - next[i]) == 0)printf("%d %d\n",i + 1, (next[i] + 1) / (i - next[i]) + 1);}}printf("\n");}return 0;}

原创粉丝点击