1. 程式人生 > >POJ 2406 - Power Strings - [KMP求最小循環節]

POJ 2406 - Power Strings - [KMP求最小循環節]

abcd for each 題解 blog 分享圖片 %d power exp clas

題目鏈接:http://poj.org/problem?id=2406

Time Limit: 3000MS Memory Limit: 65536K

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 should print the largest n such that s = a^n for some string a.

Sample Input

abcd
aaaa
ababab
.

Sample Output

1
4
3

題意:

求給出字符串,最多是多少個循環節組成的。

題解:

利用len % (len-Next[len]) == 0的話,len-Next[len]是最小循環節長度的性質。

AC代碼:

#include<cstdio>
#include<cstring>
using namespace std;

const int MAXpat = 1000000+5;

char pat[MAXpat];
int Next[MAXpat],len;

void getNext()
{
    int i=0, j=-1
; len=strlen(pat); Next[0]=-1; while(i<len) { if(j == -1 || pat[i] == pat[j]) Next[++i]=++j; else j=Next[j]; //printf("now i=%d j=%d next[%d]=%d pat[%d]=%c\n",i,j,i,Next[i],i,pat[i]); } } int main() { while(scanf("%s",pat)) { if(pat[0]==. && pat[1]==\0) break; getNext(); if(len%(len-Next[len])==0) printf("%d\n",len/(len-Next[len])); else printf("1\n"); } }

註意:

①當且僅當len%(len-Next[len])==0時,len-Next[len]才是最小循環節長度。

②關於Next數組,我覺得這個圖很不錯的展示了Next數組存儲了啥:

  技術分享圖片

POJ 2406 - Power Strings - [KMP求最小循環節]