POJ-2406 Power Strings(KMP)
Posted 真正的强者,从不埋怨黎明前的黑暗!!!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ-2406 Power Strings(KMP)相关的知识,希望对你有一定的参考价值。
题目描述:
Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = "" (the empty string) and a^(n+1) = a*(a^n).
Input
Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.
Output
For each s you should print the largest n such that s = a^n for some string a.
Sample Input
abcd aaaa ababab .Sample Output
1 4 3
题目大意:给一个字符串,求最短的循环节的长度.
题目分析:使用kmp算法求出next数组,length-1-next[length-1]即为最短循环节的长度.
AC代码如下:
# include<iostream> # include<cstdio> # include<cstring> # include<algorithm> using namespace std; const int N=1000000; int nxt[N+5]; char s[N+5]; void getNext(char *s) { int n=strlen(s); nxt[0]=nxt[1]=0; for(int i=1;i<n;++i){ int j=nxt[i]; while(j&&s[i]!=s[j]) j=nxt[j]; nxt[i+1]=(s[i]==s[j])?j+1:0; } } bool check(int x) { int n=strlen(s); for(int i=0;i+x<n;i+=x){ int j=i+x,k=i; while(k<i+x){ if(s[k]!=s[j]) return false; ++j,++k; } } return true; } void solve() { int n=strlen(s); if(n==1) printf("1\n"); else{ int x=n-1-nxt[n-1]; if(n%x) printf("1\n"); else{ if(check(x)) printf("%d\n",n/x); else printf("1\n"); } } } int main() { //freopen("in.txt","r",stdin); while(~scanf("%s",s)&&!strchr(s,‘.‘)) { getNext(s); solve(); } return 0; }
以上是关于POJ-2406 Power Strings(KMP)的主要内容,如果未能解决你的问题,请参考以下文章