HDU--4821(字符串哈希)


题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4821


用到了BKD字符串哈希的方法,一直不是很会哈希,总是用map,但是很显然,map并不是万能的。

用哈希的方法可以递推的求出所有子串的哈希值,最后用map维护答案即可;注意下long long 




#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<vector>
#include<map>
#include<climits>
using namespace std;
typedef long long ll;
typedef unsigned long long llu;

const int maxd=1e5+5;
const int seed=31;
const int INF = 0xffffffff;
///===================
char str[maxd];
llu k[maxd],_hash[maxd];
map<llu,int> s;
int M,L;

void BKD_hash(int len)
{
    k[0]=1;
    for(int i=1; i<=L; i++)
        k[i]=k[i-1]*seed;
    for(int i=len-1; i>=0; i--)
        _hash[i]=_hash[i+1]*seed+(str[i]-'a'+1);
}

int main()
{
    while(scanf("%d%d",&M,&L)==2)
    {
        scanf("%s",str);
        int len=strlen(str),cnt=0;
        BKD_hash(len);
        for(int i=0; i<L && M*L+i<len; i++)
        {
            s.clear();
            for(int j=i; j<M*L+i; j+=L)
            {
                llu id=_hash[j]-_hash[j+L]*k[L];
                s[id]++;
            }
            if(s.size()==M) cnt++;

            for(int j=M*L+i; j<len-L+1; j+=L)
            {
                llu head=j-M*L;
                llu id=_hash[head]-_hash[head+L]*k[L];
                s[id]--;
                if(s[id]==0) s.erase(id);
                llu id2=_hash[j]-_hash[j+L]*k[L];
                s[id2]++;

                if(s.size()==M) cnt++;
            }
        }

        printf("%d\n",cnt);
    }
    return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值