HDU 4821 String(字符串哈希)

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

题意:

给出M和L,和一个字符串S。要求找出S的子串中长度为L*M,并且可以分成M段,每段长L,并且M段都不相同的子串个数。哈希过后, 若Hash[i]-Hash[i+L]*K[L] == Hash[j]-Hash[j+L]*k[L], 则说明串s[i...i+L-1] 和串s[j....j+L-1]是相同的。

#include<stdio.h>
#include<string.h>
#include<map>
#include<algorithm>
using namespace std;
typedef unsigned long long ULL;
#define SEED 31//这个数一般为素数 如1331, 1000000007等

const int maxn = 1e5 + 100;
ULL Hash[maxn], K[maxn];
map<ULL, int> st;
char s[maxn];
int main()
{
    int M, L, len;
    while(~scanf("%d%d", &M, &L))
    {
        scanf("%s", s);
        len = strlen(s);
        Hash[len] = 0;
        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 + (s[i]-'a'+1);
        }
        int res = 0;
        for(int i = 0; i<L && i+M*L<len; i++)
        {
            st.clear();
            for(int j = i; j < M*L+i; j+=L)
            {
                st[Hash[j]-Hash[j+L]*K[L]]++;
            }
            if(st.size() == M)
                res++;
            for(int j = M*L+i; j <= len-L; j+=L)
            {
                int head = j - M*L;
                st[Hash[head]-Hash[head+L]*K[L]]--;
                if(st[Hash[head]-Hash[head+L]*K[L]] == 0)
                    st.erase(Hash[head]-Hash[head+L]*K[L]);
                st[Hash[j]-Hash[j+L]*K[L]]++;
                if(st.size() == M)
                    res++;
            }
        }
        printf("%d\n", res);
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值