poj 2406 Power Strings【KMP】,poj2406

來源:互聯網
上載者:User

poj 2406 Power Strings【KMP】,poj2406
點擊開啟題目
Power Strings

Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 33548   Accepted: 13935

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.題目翻譯意:給一個字串S長度不超過10^6,求最大的n使得S由n個相同的字串a串連而成,如:"ababab"則由n=3個"ab"串連而成,"aaaa"由n=4個"a"串連而成,"abcd"則由n=1個"abcd"串連而成。

解題思路:假設S的長度為len,則S存在迴圈子串,若且唯若,len可以被len - next[len]整除,最短迴圈子串為S[len - next[len]]
利用KMP演算法,求字串的特徵向量next,若len可以被len - next[len]整除,則最大迴圈次數n為len/(len - next[len]),否則為1
#include<cstdio>#define maxn 1000002char str[maxn];int next[maxn],len,s;void GetNext(){    int i=0,j=-1;    next[0]=-1;    while(str[i]){        if(j==-1||str[i]==str[j]){            ++i;++j;next[i]=j;        }else j=next[j];    }    len=i;}int main(){    while(scanf("%s",str)==1){        if(str[0]=='.') break;        GetNext();        s=len-next[len];        if(len%s==0) printf("%d\n",len/s);        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.