Language:DefaultPower strings
Time limit:3000 Ms |
|
Memory limit:65536 K |
Total submissions:33205 |
|
Accepted:13804 |
Description 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 shoshould print the largest N such that S = a ^ N for some string.Sample Input abcdaaaaababab. Sample output 143 Hint This problem has huge input, use scanf instead of CIN to avoid time limit exceed.Source Waterloo local 2002.07.01 |
The length of a string s cannot exceed 10 ^ 6. Calculate the maximum n so that S is connected by N identical strings a, for example: "ababab" is composed of N = 3 "AB" connections. "aaaa" is composed of N = 4 "A" connections, "ABCD" is connected by n = 1 "ABCD.
Theorem: if the length of S is Len, S has a circular substring. if and only, Len can be divisible by Len-next [Len, the shortest loop substring is s [Len-next [Len]
Idea: Use the KMP algorithm to obtain the next feature vector of a string. If Len can be divisible by Len-next [Len, the maximum number of cycles N is Len/(LEN-next [Len]); otherwise, it is 1.
Code:
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#include <string>#include <map>#include <stack>#include <vector>#include <set>#include <queue>#pragma comment (linker,"/STACK:102400000,102400000")#define maxn 1005#define MAXN 2005#define mod 1000000009#define INF 0x3f3f3f3f#define pi acos(-1.0)#define eps 1e-6typedef long long ll;using namespace std;int N;int nextval[1000010];char str[1000010];int get_nextval(){ int i=0; int len=strlen(str); int j=-1; nextval[i]=-1; while (i<len) { if (j==-1||str[i]==str[j]) { i++; j++; nextval[i]=j; } else j=nextval[j]; } if ((len)%(len-nextval[len])==0) return len/(len-nextval[len]); else return 1;}int main(){ while (scanf("%s",str)) { if (str[0]=='.') return 0; printf("%d\n",get_nextval()); } return 0;}
Power strings (poj 2406 KMP)