hdu4821 String (字符串hash + map)

题目:

一个字符串S,找出 S 有几个子串满足如下要求:

  • 子串长度是M*L,即由M个长度为L的小子串相连而成。
  • 这M个小子串互不相同。

分析:

最朴素的想法肯定是枚举1~n-L+1依次作为子串的开始,然后算出它之后的M个长度为L的串的值是否相同。这样的时间复杂度是O(n * M),不太能接受,尝试优化。
为了方便描述我们让M = L = 3
假设我们已经得到了以第1个字符开头的3个长L的串,###@@@^^^,现在想算下一个,只需往后加上&&&,去掉###,就O(1)的复杂度得到了@@@^^^&&&这种新串,以此类推。这样,得到一个串的复杂度就变为了O(1)而不是O(M),因为我们利用了上一个串的结果。
这样,只需要枚举这个不断“去尾添头”的串从哪开始即可。显然,为了不重复,枚举1~L作为开头即可。
另一个值得注意的地方,map可以巧妙地用了存储大数出现的次数。

代码:

#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;
#define ms(a,b) memset(a,b,sizeof(a))
typedef long long ll;
typedef unsigned long long ull;
const int MAXN = 1e5 + 5;
const double EPS = 1e-8;
const int INF = 0x3f3f3f3f;
const int base = 163;
char s[MAXN];
int M, L, n;
ull Hash[MAXN], p[MAXN], pre[MAXN];
ull getHash(int l, int r, ull Hash[]) {
    return Hash[r] - Hash[l - 1] * p[r - l + 1];
}
void makeHash() {
    p[0] = 1;
    for (int i = 1; i <= MAXN; i++) {
        p[i] = p[i - 1] * base;
    }
    Hash[0] = 0;
    for (int i = 1; i <= n; i++) {
        Hash[i] = Hash[i - 1] * base + s[i] - 'a' + 1;
    }
    for (int i = 1; i <= n - L + 1; i++) {
        pre[i] = getHash(i, i + L - 1, Hash);
    }
}
int main() {
    while (~scanf("%d%d", &M, &L)) {
        scanf("%s", s + 1);
        n = strlen(s + 1);
        makeHash();
        int ans = 0;
        for (int i = 1; i <= L && i + M * L - 1 <= n; i++) {
            map<ull, int> mp;
            for (int j = 0; j < M; j++) {
                ull h = pre[i + j * L];
                mp[h] ++;
            }
            if ((int)mp.size() == M)    ans ++;
            for (int j = i + M * L; j + L - 1 <= n; j += L) {
                ull h = pre[j - M * L];
                mp[h]--;
                if (!mp[h]) mp.erase(h);
                h = pre[j];
                mp[h] ++;
                if ((int)mp.size() == M)    ans ++;
            }
        }
        printf("%d\n", ans);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值