power Strings(next数组求循环节长度)

时间:2022-07-28
本文章向大家介绍power Strings(next数组求循环节长度),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题意描述

Given two strings a and b we define ab to be their concatenation. For example, if a = “abc” and b = “def” then ab = “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).

字符串可以由某个子串循环n次得到,求最大的n

思路

可以预处理出next数组,字符串具有长度为len的循环元的充要条件是len能整除i并且S[len+1,i]=S[1,i-len],具体证明过程就不放出来了,可以参照李煜东大佬的证明过程。 关于此题放一个比较好的博客 洛谷

再补充几个定理:

1.假设S的长度为len,则S存在最小循环节,循环节的长度L为len-next[len],子串为S[0…len-next[len]-1]。 2.如果不能,说明还需要再添加几个字母才能补全。需要补的个数是循环个数L-len%L=L-(len-L)%L=L-next[len]%L,L=len-next[len]。 3.如果len可以被len - next[len]整除,则表明字符串S可以完全由循环节循环组成,循环周期T=len/L。

AC代码

#include<iostream>
#include<algorithm>
#include<cstring>
#define x first
#define y second
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long LL;
const int N=1e6+10;
const int M=150;
const int INF=0x3f3f3f3f;
const int MOD=998244353;
int ne[N];
char s[N];
void solve(){
    while(cin>>s+1){
        for(int i=1;i<=strlen(s+1);i++){
            if(s[i]=='.') return;
        }
        memset(ne,0,sizeof ne);
        int n=strlen(s+1);
        for(int i=2,j=0;i<=n;i++){
            while(j && s[i]!=s[j+1]) j=ne[j];
            if(s[i]==s[j+1]) j++;
            ne[i]=j;
        }
        if(n%(n-ne[n])==0) cout<<n/(n-ne[n])<<endl;
        else cout<<1<<endl;
    }
}
int main(){
    IOS;
    solve();
    return 0;
}