题目链接:https://vjudge.net/problem/POJ-2406
kmp学习:https://blog.csdn.net/starstar1992/article/details/54913261/
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
Hint
This problem has huge input, use scanf instead of cin to avoid time limit exceed.
题目大意:问你一个子串的最多多少次方能构成完整的串
思路:其实这题本人是没有想到next数组能直接求出来的 ,后来看了一下题解,大概意思如下:
比如: ababab,显然最后一位的next数组是3(这里以0开始),所以0~3位和2~5位是一样的,所以0~1和2~3是一样的,2~3和4~5是一样的,所以最多次方数就是3个
比如:ababa,显然最后一位的next数组是3,所以0~2位和2~4位是一样的,所以0~1和2~3是一样的,但是还剩下一位,所以最大只能是1
综上所述,其实就是求最后一位的next数组,然后总长减去它,看总长是否能够整除这个值,能的话直接输出整除的值,不能的话,答案就是1
看一下证明:
-----------------------------
-----------------------------
k m x j i
由上,next【i】=j,两段红色的字符串相等(两个字符串完全相等),s[k....j]==s[m....i]
设s[x...j]=s[j....i](xj=ji)
则可得,以下简写字符串表达方式
kj=kx+xj;
mi=mj+ji;
因为xj=ji,所以kx=mj,如下图所示
-------------
-------------
k m x j
看到了没,此时又重复上面的模型了,kx=mj,所以可以一直这样递推下去
所以可以推出一个重要的性质len-next[i]为此字符串的最小循环节(i为字符串的结尾),另外如果len%(len-next[i])==0,此字符串的最小周期就为len/(len-next[i]);
证明来源:https://blog.csdn.net/hp_satan/article/details/18085919
看代码:
#include<iostream> #include<string.h> #include<map> #include<cstdio> #include<cstring> #include<stdio.h> #include<cmath> #include<ctype.h> #include<math.h> #include<algorithm> #include<set> #include<queue> typedef long long ll; using namespace std; const ll mod=1000; const int maxn=1e8+10; const int maxk=5e3+10; const int maxx=1e4+10; const ll maxe=1000+10; #define INF 0x3f3f3f3f3f3f #define Lson l,mid,rt<<1 #define Rson mid+1,r,rt<<1|1 char a[maxn]; int next[maxn]; void cal_next() { next[0]=-1; int k=-1; int len=strlen(a); for(int i=1;i<len;i++) { while(k>-1&&a[k+1]!=a[i]) { k=next[k]; } if(a[k+1]==a[i]) k++; next[i]=k; } } int main() { //while(cin>>a) while(scanf("%s",a)!=EOF) { if(a[0]==‘.‘) break; cal_next(); int len=strlen(a); if(len%(len-next[len-1]-1)==0) printf("%d\n",len/(len-next[len-1]-1)); else printf("1\n"); } return 0; }
原文地址:https://www.cnblogs.com/caijiaming/p/9652254.html