hdu3746kmp循環節

題目大意:

給定一個字符串s, 問至少在s的後面添加幾個字符才能使s成爲以一個循環節至少出現兩次的字符串。

思路:

利用kmp算法的next數組求循環節。假設當前字符串s的長度爲n

若next[n] ==0,則需要添加n個字符,使之變爲最小循環節出現兩次的新的字符串。

        若n%(n-next[n]) == 0,則表示當前字符串s就是一個循環串,其最小循環節的長度爲(n - next[n])由下圖可以很容易明白這一點



否則的話  可以分爲兩種情況

(1)   next[n] >n/2


則這種情況需要至少添加(n - next[n])-  n%(n - next[n])個字符

(2)next[n] < =n/2



這種情況需要添加n - 2*next[n] 個字符,            n - 2*next[n]     ==   (n - next[n]) - n % (n - next[n])


hdu3746AC代碼

#include <cstdio>
#include <cstring>

const int maxn = 100005;
char p[maxn];
int n,next[maxn];
void getnext(char* p)
{
    next[1]=0;
    int k = 0;
    for(int i=2;i<=n;i++)
    {
        while(k!=0 && p[k+1] != p[i])
            k = next[k];
        if(p[k+1] == p[i]) k++;
        next[i] = k;
    }
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%s", p+1);
        n = strlen(p+1);
        getnext(p);
        int ans;
        if(next[n] == 0)
           ans = n;
        else if(n % (n-next[n]) == 0)
        {
            ans = 0;
        }
        else
        {
            ans = (n-next[n]) - next[n] % (n - next[n]);
        }
        printf("%d\n",ans);
    }
    return 0;
}


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