1. 程式人生 > >kuangbin KMP G題

kuangbin KMP G題

G - Power Strings

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求最小迴圈節應用。
注意判斷條件。

程式碼:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int MAXN = 1000000+100;

char str[MAXN];
int len;
int nt[MAXN];

void getNext()
{
    nt[0] = -1;
    int i = 0, j = -1;
    while (i <= len)
    {
        if
(j == -1 || str[i] == str[j]) { nt[++i] = ++j; } else { j = nt[j]; } } } int main() { while(scanf("%s",str)!=EOF) { if(str[0]=='.') break; len = strlen(str); getNext(); if(nt[len]==0) { cout
<<1<<endl; continue; } int t = len-nt[len]; if(len%t) { cout<<1<<endl; } else cout<<len/t<<endl; } return 0; }