HDU - 4821 String(字符串hash+ map判重)

点击打开题目链接

题目大意:

给出两个整数M和L及一个字符串s,找到s的子串使得满足:
1.子串长度为L*M;
2.子串可以分成M个小子串,每个长度L,且M个子串互不相同;
求满足条件的s的子串的数量。

思路:

基本思路是先用BKDRhash函数处理字符串。然后字符串从后往前遍历求解hash值,利用map判重的特点,存储子串中每个小子串的hash值,如果等于M则ans++。然后思考怎样遍历所有的子串,如果一个个枚举子串起始位置肯定超时。所以可以只枚举最开始的L个子串,然后往后延伸,每增加一个小子串之前,去掉最开始的那个小子串,类似于滑动窗口处理。(ull的数据会溢出会自动取余。所以不用担心溢出问题。)

代码:

#include<bits/stdc++.h>

using namespace std;
typedef unsigned long long ull;
const int maxn = 1e5 + 5;
const int seed = 31;
ull _base[maxn], _hash[maxn];
map<ull, ull> mp;
int M, L;
string s;

ull str_hash(int l, int r) {
    return _hash[l] - _hash[r+1] * _base[r-l+1];
}

int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    _base[0] = 1;
    for(int i = 1; i < maxn; i++) _base[i] = _base[i-1] * seed;
    while(cin >> M >> L) {
        cin >> s;
        int len = s.length();
        _hash[len] = 0;
        for(int i = len-1; i >= 0; i--) _hash[i] = _hash[i+1] * seed + (s[i] - 'a' +1);
        int ans = 0;
        for(int i = 0; i < L && i + M*L < len; i++) {
            mp.clear();
            for(int j = i; j < i + M*L; j += L) {
                mp[str_hash(j, j+L-1)]++;
            }
            if(mp.size() == M) ans++;
            for(int j = i + M*L; j <= len - L; j += L) {
                mp[str_hash(j-M*L, j-M*L+L-1)]--;
                if(mp[str_hash(j-M*L, j-M*L+L-1)] == 0) mp.erase(str_hash(j-M*L, j-M*L+L-1));
                mp[str_hash(j, j+L-1)]++;
                if(mp.size() == M) ans++;
            }
        }
        cout << ans << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/l1832876815/article/details/81224723
今日推荐