poj1961(kmp算法next数组应用)
题目链接:https://vjudge.net/problem/POJ-1961
题意:给定一个长为n的字符串(n<=1e6),对于下标i(2<=i<=n),如果子串s(1...i)是周期子串,输出其最大周期。
思路:
考察对kmp算法中next数组的定义掌握,如果(i+1)%(i-j)==0 && (i+1)/(i-j) > 1,那么该子串即为满足条件。
AC代码:
#include<cstdio> #include<algorithm> #include<cstring> using namespace std; const int maxn=1e6+5; int n,cas,nex[maxn]; char s[maxn]; void get_next(){ int j; j=nex[0]=-1; for(int i=1;i<n;++i){ while(j>-1&&s[i]!=s[j+1]) j=nex[j]; if(s[i]==s[j+1]) ++j; nex[i]=j; if((i+1)%(i-j)==0&&(i+1)/(i-j)>1) printf("%d %d\n",i+1,(i+1)/(i-j)); } } int main(){ while(scanf("%d",&n),n){ scanf("%s",s); printf("Test case #%d\n",++cas); get_next(); printf("\n"); } return 0; }
相关推荐
troysps 2020-05-30
shawsun 2020-03-23
wulaxiaohei 2019-12-29
rein0 2019-12-14
ustbfym 2019-11-03
Happyunlimited 2020-05-01
RememberMePlease 2020-04-30
yedaoxiaodi 2020-01-25
蜗牛慢爬的李成广 2020-01-11
yedaoxiaodi 2020-01-02
darlingtangli 2019-11-17
seekerhit 2019-11-05
Happyunlimited 2019-11-04
HTML学堂码匠 2019-04-03
KDF000 2013-02-14