题意:给一个字符串,把它分成尽量多的K个子串,设子串
s
u
b
s
1
,
s
u
b
s
2
…
s
u
b
s
k
subs_1, subs_2…subs_k
subs1,subs2…subsk,要求满足
s
u
b
s
i
=
s
u
b
s
k
−
i
+
1
subs_i = subs_{k - i + 1}
subsi=subsk−i+1,求
K
m
a
x
K_{max}
Kmax
思路:两边向中间贪心,如果遇到相同的子串就插入分割线,同时K加2,如果直接比较子串,复杂度达到
n
2
n^2
n2,改用字符串哈希比较,复杂度降至
n
n
n。
#include<iostream>
#include<algorithm>
using namespace std;
typedef unsigned long long ull;
const int N=1e6+100;
ull Hash[N],p[N];
int n;
string str;
void _hash()
{
Hash[0]=0;
for(int i=1;i<=n;i++)
{
Hash[i]=Hash[i-1]*131+str[i]-'0'+1;
}
p[0]=1;
for(int i=1;i<=n;i++)
p[i]=p[i-1]*131;
}
int main()
{
cin>>str;
n=str.size();
str=" "+str;
_hash();
int l=1,r=n;
int start=1,end=n;
int ans=0;
while(l<r)
{
ull a=Hash[l]-Hash[start-1]*p[l-start+1];
ull b=Hash[end]-Hash[r-1]*p[end-r+1];
if(a==b)
{
ans+=2;
start=l+1;
end=r-1;
}
l++, r--;
}
if(l==r)
ans++;
if(start < end&&l>r) ans++;
cout<<ans<<endl;
return 0;
}