upc10214 2019我要变强弱校联训赛第十场I 字符串哈希

题意:给一个字符串,把它分成尽量多的K个子串,设子串 s u b s 1 , s u b s 2 … s u b s k subs_1, subs_2…subs_k subs1,subs2subsk,要求满足 s u b s i = s u b s k − i + 1 subs_i = subs_{k - i + 1} subsi=subski+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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值