前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >power Strings(next数组求循环节长度)

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

作者头像
dejavu1zz
发布2020-10-23 15:22:14
8490
发布2020-10-23 15:22:14
举报
文章被收录于专栏:奇妙的算法世界

题意描述

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代码

代码语言:javascript
复制
#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;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/07/15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题意描述
  • 思路
  • AC代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档