HDU 4821 String 字符串哈希

本文介绍了一种使用哈希方法统计特定长度且各子串互不重复的子串数量的算法。通过滑动窗口和哈希表的方式高效地解决了问题。
题意:

给一个字符串\(s\),统计长为\(M*L\)的字串的个数。如果将该字串看成\(M\)个长为\(L\)的串拼接起来,那么这\(M\)个串必须互不相同。

分析:

枚举串的开头,然后用map来维护这\(M\)个hash值。
我用的《训练指南》上的hash方法:
定义一个\(H(n)=\sum{s_i x^{i-n}}\)
\(i\)开头的长为\(L\)的字串的hash值为:\(H(i)-H(i+L)x^L\)
hash值为unsigned long long类型,这样就不用在代码中取模了。

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

const int maxl = 100000 + 10;
char s[maxl];
int n, M, L;

const int x = 123;
unsigned long long H[maxl], xp[maxl];

map<unsigned long long, int> cnt;

unsigned long long hashcode(int s, int L) {
    return H[s] - H[s+L] * xp[L];
}

int main() {
    xp[0] = 1;
    for(int i = 1; i < maxl; i++) xp[i] = xp[i-1] * x;

    while(scanf("%d%d", &M, &L) == 2) {
        scanf("%s", s);
        n = strlen(s);

        H[n] = 0;
        for(int i = n - 1; i >= 0; i--) H[i] = H[i+1] * x + s[i] - 'a';

        long long ans = 0;
        for(int s = 0; s + M * L <= n && s < L; s++) {
            cnt.clear();
            for(int i = s; i < s + L * M; i += L)
                cnt[hashcode(i, L)]++;
            if(cnt.size() == M) ans++;
            for(int i = s + L * M; i + L <= n; i += L) {
                int head = i - L * M;
                unsigned long long p = hashcode(head, L);
                if(cnt[p] == 1) cnt.erase(p);
                else cnt[p]--;
                cnt[hashcode(i, L)]++;
                if(cnt.size() == M) ans++;
            }
        }

        printf("%lld\n", ans);
    }

    return 0;
}

转载于:https://www.cnblogs.com/AOQNRMGYXLMV/p/4919367.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值