Codeforces Round #166 (Div. 2) D. Good Substrings (前缀和)

原题地址:http://codeforces.com/contest/271/problem/D
题意:每个字母有被赋予好坏的含义,现在要求某一个字符串有多少不同的子串的中的”坏字母”的数量 <= k

思路;这题需要先对字符串进行预处理在 1 i 的范围内有多少坏的字母,这样子在后面枚举每一个子串的时候就能快速判断是否合法.判断字符串是否相同用哈希即可.

#include <bits/stdc++.h>
#include <cmath>
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#include <stack>
#include <set>
#include <map>
#include <cctype>
#define eps 1e-8
#define INF 0x3f3f3f3f
#define MOD 1e9+7
#define PI acos(-1)
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define CLR(x,y) memset((x),y,sizeof(x))
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int seed = 131;
const int maxn = 1e5 + 5;
char a[maxn];
char s[maxn];
int sum[maxn], k;
unordered_map<ull, int>mp;
int main() {
    scanf("%s%s%d", a + 1, s + 1, &k);
    int len = strlen(a + 1);
    for(int i = 1; i <= len; i++) {
        sum[i] = sum[i - 1] + (s[a[i] - 'a' + 1] == '0');
    }
    for(int i = 1; i <= len; i++) {
        ull h = 0;
        for(int j = i; j <= len; j++) {
            if(sum[j] - sum[i - 1] > k) continue;
            h = h * seed + a[j];
            mp[h]++;
        }
    }
    printf("%d\n", mp.size());
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yiqzq/article/details/81536040