poj_2406 Power Strings(KMP求週期子串)

【題目描述】

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).

【輸入輸出】

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.

For each s you should print the largest n such that s = a^n for some string a.

【輸入樣例】

abcd
aaaa
ababab
.

【輸出樣例】

1
4
3

【我的解法】

本題考察對KMP算法中next數組的應用:若記字符串長度爲sLen,則next[sLen]保存的值爲整個串中的最大公共前綴後綴的長度,若字符串由循環子串組成,則sLen-next[sLen]則爲最小循環節的長度。

通過下面的測試結果,可以更好理解next數組:


下面附上代碼。

#include <stdio.h>
#include <string.h>

void getNext(char t[], long int next[], long int tLen)
{
    int i=0, j=-1;
    next[i]=j;

    while (i<tLen)
        if (j==-1 || t[i]==t[j])
        {
            i++;j++;
            if (t[i]!=t[j]) next[i]=j; else next[i]=next[j];
        }
        else j=next[j];
}

int main()
{
    char s[1000001];
    long int next[1000001];
    while (scanf("%s",s)!=EOF)
        if (s[0]!='.')
    {
        long int sLen=strlen(s);
        getNext(s,next,sLen);
        if (sLen%(sLen-next[sLen])==0) printf("%ld\n",sLen/(sLen-next[sLen]));
        else printf("1\n");
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章