poj 2406 Power Strings(KMP求迴圈次數)

來源:互聯網
上載者:User

標籤:kmp   poj   

題目連結:http://poj.org/problem?id=2406


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

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

題意:

求最小子串的迴圈次數;

思路:(轉)

KMP,next[]表示模式串如果第i位(設str[0]為第0位)與文本串第j位不匹配則要回到第next[i]位繼續與文本串第j位匹配。則模式串第1位到next[n]與模式串第n-next[n]位到n位是匹配的。所以思路和上面一樣,如果n%(n-next[n])==0,則存在重複連續子串,長度為n-next[n]。

例如:a    b    a    b    a    b

next:-1   0    0    1    2    3    4

next[n]==4,代表著,首碼abab與尾碼abab相等的最長長度,這說明,ab這兩個字母為一個迴圈節,長度=n-next[n];


代碼如下:

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;#define MAXN 1000017int next[MAXN];int len;void getnext( char s[]){    int i = 0, j = -1;    next[0] = -1;    while(i < len)    {        if(j == -1 || s[i] == s[j])        {            i++,j++;            next[i] = j;        }        else            j = next[j];    }}int main(){    char ss[MAXN];    int length;    while(~scanf("%s",ss))    {        if(ss[0] == '.')            break;        len = strlen(ss);        getnext(ss);        length = len - next[len];//注意        if(len%length == 0)            printf("%d\n",len/length);        else            printf("1\n");    }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.