标签:string type time cee long math put 完全 repr
Given two strings a and b we define ab to be their concatenation. For example, if a = "abc" and b = "def" then ab = "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.
题目描述:
求一个字符串能分成最多多少个相同子串。(完全分割成相同的n份,求n)
分析:
根据kmp算法的next的性质。next[strlen-1]+1就是整个字符串最大前后缀相同的长度。要计算周期,设d=strlen-(next[strlen-1]+1),那么周期T=strlen/d(如果strlen%d==0),否则就不能分。
证明如下:
代码:
#include<iostream> #include<algorithm> #include<cstring> #include<cstdio> #include<sstream> #include<vector> #include<stack> #include<deque> #include<cmath> #include<map> using namespace std; typedef long long ll; const int maxn=1e6+6; int neet[maxn]; void getnext(string ptr,int len) { neet[0]=-1; int k=-1; for(int i=1;i<len;i++) { while(k>-1&&ptr[k+1]!=ptr[i]) k=neet[k]; if(ptr[k+1]==ptr[i]) k++; neet[i]=k; } } int main() { while(1) { char s[maxn]; scanf("%s",&s); if(s[0]==‘.‘&&strlen(s)==1) break; int n=strlen(s); getnext(s,n); int d=n-(neet[n-1]+1); if(n%d==0) printf("%d\n",n/d); else printf("1\n"); } return 0; }
标签:string type time cee long math put 完全 repr
原文地址:https://www.cnblogs.com/studyshare777/p/12604467.html