http://acm.hdu.edu.cn/showproblem.php?pid=6740
从后往前维护fail数组,枚举已出现的循环节总长度更新答案即可。
1 #define bug(x) cout<<#x<<" is "<<x<<endl 2 #define IO std::ios::sync_with_stdio(0) 3 #define ull unsigned long long 4 #include <bits/stdc++.h> 5 #define iter ::iterator 6 #define pa pair<int,ll> 7 #define pp pair<int,pa> 8 using namespace std; 9 #define ll long long 10 #define mk make_pair 11 #define pb push_back 12 #define se second 13 #define fi first 14 #define ls o<<1 15 #define rs o<<1|1 16 const int N=1e7+5; 17 ll mod=998244353; 18 ll a,b; 19 char s[N],t[N]; 20 int fail[N]; 21 void kmp(){ 22 int n=strlen(t); 23 fail[0]=-1; 24 fail[1]=0; 25 int i=1,j=0; 26 while(i<n&&j<n){ 27 if(j==-1||t[i]==t[j])fail[++i]=++j; 28 else j=fail[j]; 29 } 30 } 31 int main(){ 32 while(~scanf("%lld%lld%s",&a,&b,s)){ 33 int n=strlen(s); 34 int m=0; 35 for(int i=n-1;i>0;i--){ 36 if(s[i]=='.')break; 37 t[m++]=s[i]; 38 } 39 kmp(); 40 ll ans=a-b; 41 for(int i=2;i<=m;i++){ 42 ans=max(ans,a*i-b*(i-fail[i])); 43 } 44 printf("%lld ",ans); 45 } 46 }