2019ccpc秦皇岛 MUV LUV EXTRA (kmp求循环节)

传送门

我又是我了!我不自闭了!
死磕了三四个小时忍住没看题解,终于做出来了!…尽管这个题被大家称为水题…



思路:kmp求循环节,要求的循环节必须是在后缀中循环的,而我们正常求出的循环节,是在前缀中循环的,必须把我们的字符串倒过来求解。循环节的长度:i - nex[i]
当前循环的字符数:i

代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm> 
using namespace std;
typedef long long ull;
const int N = 1e7+10 , inf = 1e18;
int nex[N];
int n;
void get_next(string s)
{
	for(int i=2,j=0;i<=n;i++)
	{
		while(s[i]!=s[j+1] && j) 
			j=nex[j];
		if(s[i]==s[j+1]) j++;
		nex[i]=j;
	}
}
int main()
{
	cin.tie(0);
	ios::sync_with_stdio(false);
	ull a,b;
	string s;
	while(cin>>a>>b)
	{
		cin>>s;
		for(int i=0;i<s.size();i++)
			if(s[i]=='.') 
			{
				s=s.substr(i+1);break;
			}
		n=s.size();
		reverse(s.begin(),s.end());
		s=" "+s;
		get_next(s);
		ull ans=-inf;
		for(int i=1;i<=n;i++)
		{
			ull len=i-nex[i],len2=i;
			ans=max(ans,len2*a-len*b);
		}
		cout<<ans<<endl;
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章