Hdu 4821 hash+map判重

题意:给定一个字符串,找这样的子串数,长为l*m,能分解成m个长为l的不同子串。
做法:算出所有长为l的hash值,分成l组,跑一遍,用map做一下判重。
代码:

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <map>
#include <iostream>
using namespace std;

typedef unsigned long long ull;

const int maxn=100007;

ull mhash[maxn];
ull seed=1e9+7;
char str[maxn];
int m, l;
int len;

int main()
{
    while(~scanf("%d%d%s", &m, &l, str)){
        len=strlen(str);
        ull ux=1;
        for(int i=1;i<=l;i++)ux*=seed;
        ull tmp=0;
        for(int i=0;i<l;i++)tmp=tmp*seed+str[i];
        mhash[0]=tmp;
        for(int i=0;i+l<len;i++){
            mhash[i+1]=mhash[i]*seed+str[i+l]-str[i]*ux;
        }
        //for(int i=0;i<=len-l;i++)
        //  cout<<hash[i]<<'\n';
        int ans=0;
        for(int i=0;i<l;i++){
            int cnt=0;
            map<ull, int>mp;
            bool ok=true;
            for(int j=i;j<=i+l*(m-1);j+=l){
                if(j>len-l){
                    ok=false;break;
                }
                mp[mhash[j]]++;
                if(mp[mhash[j]]==2)cnt++;
            }
            if(!ok)break;
            if(cnt==0)ans++;
            int j=i+l*(m-1);
            while(1){
                j+=l;
                if(j>len-l)break;
                mp[mhash[j]]++;
                if(mp[mhash[j]]==2)cnt++;
                mp[mhash[j-l*m]]--;
                if(mp[mhash[j-l*m]]==1)cnt--;
                if(cnt==0)ans++;
            }
        }
        printf("%d\n", ans);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值