hdoj 5672 String 【模拟】

来源:互联网 发布:魅可mac加盟电话 编辑:程序博客网 时间:2024/06/06 02:44

题目链接:hdoj 5672 String

有一个 10≤长度≤1,000,000 的字符串,仅由小写字母构成。求有多少个子串,包含有至少k(1≤k≤26)个不同的字母?

模拟,维护一个左端点就可以了。

AC代码:

#include <cstdio>#include <cstring>#include <algorithm>#include <iostream>using namespace std;typedef long long LL;const int MAXN = 1e6 + 10;char str[MAXN];int num[30];int main(){    int t; scanf("%d", &t);    while(t--) {        scanf("%s", str); int len = strlen(str);        int n; scanf("%d", &n);        for(int i = 0; i <= 25; i++) num[i] = 0;        LL ans = 0; int cnt = 0; int j = 0;        for(int i = 0; i < len; i++) {            int v = str[i] - 'a';            if(num[v] == 0) {                cnt++;            }            num[v]++;            if(cnt == n) {                ans += len - i;                for(; j <= i; j++) {                    v = str[j] - 'a';                    num[v]--;                    if(num[v] == 0) {                        j++; cnt--; break;                    }                    ans += len - i;                }            }            //cout << ans << ' ' << j << endl;        }        printf("%I64d\n", ans);    }    return 0;}
0 0
原创粉丝点击