kuangbin KMP G题

来源:互联网 发布:网络审核员天河 编辑:程序博客网 时间:2024/06/05 03:31

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;}
原创粉丝点击