• 1355: [Baltic2009]Radio Transmission[循环节]


    1355: [Baltic2009]Radio Transmission

    Time Limit: 10 Sec  Memory Limit: 64 MB
    Submit: 796  Solved: 538
    [Submit][Status][Discuss]

    Description

    给你一个字符串,它是由某个字符串不断自我连接形成的。 但是这个字符串是不确定的,现在只想知道它的最短长度是多少.

    Input

    第一行给出字符串的长度,1 < L ≤ 1,000,000. 第二行给出一个字符串,全由小写字母组成.

    Output

    输出最短的长度

    Sample Input

    8
    cabcabca

    Sample Output

    3

    HINT

    对于样例,我们可以利用"abc"不断自我连接得到"abcabcabc",读入的cabcabca,是它的子串

    Source

    KMP

    #include<cstdio>
    #include<cstring>
    using namespace std;
    const int N=1e6+5;
    char s1[N];int l1,fail[N];
    void get_next(){
        int p=0;fail[1]=0;
        for(int i=2;i<=l1;i++){
            while(p>0&&s1[i]!=s1[p+1]) p=fail[p];
            if(s1[i]==s1[p+1]) p++;
            fail[i]=p;
        }
    }
    int main(){
        scanf("%d",&l1);
        scanf("%s",s1+1);
        get_next();
        printf("%d",l1-fail[l1]);
        return 0;
    }

     hash

    #include<cstdio>
    #include<cstring>
    using namespace std;
    const int N=1e6+5;
    typedef long long i64;
    i64 p,P,hash_key[N];
    char s[N];int n;
    inline void get_s_key(){
        hash_key[0]=0;
        for(int i=1;i<=n;i++) hash_key[i]=hash_key[i-1]*P+s[i]-'A';
    }
    inline i64 query(int x,int y,i64 p){
        return hash_key[y]-hash_key[x-1]*p;
    }
    int main(){
        P=29;
        scanf("%d",&n);
        scanf("%s",s+1);
        get_s_key();
        p=1;
        for(int L=1;L<=n;L++){
            p*=P;
            bool flag=1;
            for(int i=L+1;i<=n/L*L;i+=L){
                if(query(i,i+L-1,p)!=hash_key[L]){
                    flag=0;break;
                }
            }
            if(!flag) continue;
            for(int i=n/L*L+1;i<=n;i++){
                if(s[i]!=s[i-n/L*L]){
                    flag=0;break;
                }
            }
            if(!flag) continue;
            printf("%d
    ",L);
            break;
        }
        return 0;
    }
  • 相关阅读:
    [uoj173]鏖战表达式
    [cf1168E]Xor Permutations
    [cf578F]Mirror Box
    [cf1261F]Xor-Set
    [loj2506]tree
    [atARC068F]Solitaire
    [atARC066F]Contest with Drinks Hard
    [cf1270I]Xor on Figures
    [cf516D]Drazil and Morning Exercise
    无题
  • 原文地址:https://www.cnblogs.com/shenben/p/6380566.html
Copyright © 2020-2023  润新知