Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 39274 | Accepted: 16309 |
Description
Input
Output
Sample Input
abcd aaaa ababab .
Sample Output
1 4 3
Hint
題意是給定一個字符串,如果把n個相同的字符串A連接在一起視爲A^n的話,求給定的字符串的最大的n。
這個題目在看的時候沒有看到最後是以.結束。。。WA了一次想了好久。
用KMP非常好求,字符串長度len減去next[len]就可以得到一個循環子串的長度。如果是len的因子的話,那麼就可以輸出字符串長度與這個循環子串的長度作爲差,如果最後發現next[len]爲len話,那麼分別是隻有一個字符,輸出len就可以。其他情況就是沒有循環子串,直接輸出1就好。
代碼如下:
/*************************************************************************
> File Name: Power_Strings.cpp
> Author: Zhanghaoran
> Mail: [email protected]
> Created Time: Thu 26 Nov 2015 04:37:26 PM CST
************************************************************************/
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;
void prekmp(char x[], int m, int nextKmp[]){
int i = 0;
int j = -1;
nextKmp[0] = -1;
while(i < m){
if(j == -1 || x[i] == x[j])
nextKmp[++ i] = ++ j;
else
j = nextKmp[j];
}
}
int nexti[1000010];
char a[1000010];
int main(void){
while(~scanf("%s", a)){
if(!strcmp(a, "."))
break;
int len = strlen(a);
prekmp(a, len, nexti);
if((len % (len - nexti[len])) == 0)
cout << len / (len - nexti[len]) << endl;
else if(len - nexti[len] == 0)
cout << len << endl;
else
cout << "1" << endl;
//for(int i = 0; i <= len;i ++)
// cout << nexti[i] << " ";
//cout << endl;
}
}