BZOJ-1355 [Baltic2009]Radio Transmission(KMP求最小循环节)
题目描述
给一个长为 \(n(1\leq n\leq 10^6)\) 的字符串,它是由某个字符串不断自我连接形成的。但是这个字符串是不确定的,求它的最短长度。
分析
经典结论:最小循环节长度为 \(n-\text{Next}[n]\)。
代码
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
char str[N+10];
int Next[N+10],n;
void get_next()
{
int j=0;
for(int i=2;i<=n;i++)
{
while(j>0&&str[i]!=str[j+1])
j=Next[j];
if(str[i]==str[j+1])
j++;
Next[i]=j;
}
}
int main()
{
cin>>n;
scanf("%s",str+1);
get_next();
cout<<n-Next[n]<<endl;
return 0;
}
/*
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
char str[N+10];
int Next[N+10],n;
void get_next()
{
int j=0;
for(int i=1;i<n;i++)
{
while(j>0&&str[i]!=str[j])
j=Next[j-1];
if(str[i]==str[j])
j++;
Next[i]=j;
}
}
int main()
{
cin>>n;
scanf("%s",str);
get_next();
cout<<n-Next[n-1]<<endl;
return 0;
}
*/
posted on 2020-11-14 16:05 DestinHistoire 阅读(73) 评论(0) 收藏 举报
浙公网安备 33010602011771号