HDU 3746 Cyclic Nacklace(KMP,最短迴圈節)

來源:互聯網
上載者:User

連結:

http://acm.hdu.edu.cn/showproblem.php?pid=3746

題目大意:

給定一個字串T, 在T後面添加x個字串(讓x最小),使得新字串由首碼字串至少迴圈兩次構成的。

例如,

abca,  只需要再添加2個字母bc, 形成abcabc,就變成了由abc迴圈兩次構成的。

分析與總結:

失配函數構造next數組的性質的應用,需要對這個有真正的理解。

對於長度為len的字串,假設已經夠造完了next數組,那麼len-next[len]就是這個字串的最小迴圈節。

如果正好len%(len-next[len])==0就說明正好組成完成的迴圈。

否則,說明還需要再添加幾個字母才能補全。

需要補的個數是迴圈個數len-next[len]-f[len]%(len-next[len]).

f[len]%(len-next[len])表示在最後一個迴圈節中已經構造了這麼多個數。


代碼:

#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int MAXN = 100005;char T[MAXN];int  f[MAXN];void getFail(char* p,int* f){    int n=strlen(p);    f[0]=f[1]=0;    for(int i=1; i<n; ++i){        int j=f[i];        while(j && p[i]!=p[j]) j=f[j];        f[i+1] = p[i]==p[j]?1+j:0;    }}int main(){    int nCase;    scanf("%d",&nCase);    while(nCase--){        scanf("%s",T);        int len=strlen(T);        getFail(T, f);        if(f[len] && len%(len-f[len])==0){            puts("0");        }        else{            int ans=(len-f[len])-f[len]%(len-f[len]);            printf("%d\n",ans);        }    }    return 0;}


 ——  生命的意義,在於賦予它意義士。

          原創 http://blog.csdn.net/shuangde800 , By
  D_Double  (轉載請標明)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.