HDU 5672 String 尺取法追赶法

String




Problem Description
There is a string  S.S only contain lower case English character.(10length(S)1,000,000)
How many substrings there are that contain at least k(1k26) distinct characters?
 

 

Input
There are multiple test cases. The first line of input contains an integer  T(1T10) indicating the number of test cases. For each test case:

The first line contains string S.
The second line contains a integer k(1k26).
 

 

Output
For each test case, output the number of substrings that contain at least  k dictinct characters.
 

 

Sample Input
2 abcabcabca 4 abcabcabcabc 3
 

 

Sample Output
0 55
 

 

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

  有一个明显的性质:如果子串(i,j)(i,j)包含了至少kk个不同的字符,那么子串(i,k),(j < k < length)(i,k),(j<k<length)也包含了至少kk个不同字符。

  因此对于每一个左边界,只要找到最小的满足条件的右边界,就能在O(1)O(1)时间内统计完所有以这个左边界开始的符合条件的子串。

  寻找这个右边界,是经典的追赶法(尺取法,双指针法)问题。维护两个指针(数组下标),轮流更新左右边界,同时累加答案即可。复杂度 O(length(S))O(length(S))。

#include<iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include<queue>
#include<algorithm>
#include<stack>
#include<cstring>
#include<vector>
#include<list>
#include<set>
#include<map>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int N = 1e6+10, M = 30005, mod = 1e9 + 7, inf = 0x3f3f3f3f;
typedef long long ll;

int T,k,H[300];
char s[N];
int main() {
    scanf("%d",&T);
    while(T--) {
        scanf("%s%d",s+1,&k);
        int n = strlen(s+1);
        memset(H,0,sizeof(H));
        int  r = 0,cnt = 0;
        ll ans = 0 ;
        for(int l = 1;l<=n;l++) {
            while(cnt<k&&r<n) {
                ++r;
                if(++H[s[r]]==1) cnt++;
            }
            if(cnt<k) break;
            ans = ans+n-r+1;
            if(--H[s[l]] == 0) --cnt;
        }
        cout<<ans<<endl;
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/zxhl/p/5423034.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值