hdu5672 String (尺取)

String

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

Input

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

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

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

分析:

假设长度为n
暴力做法:
枚举每个左区间边界L,找到恰好K个不同的值的右边界R
因为再向右边加字符肯定至少k个不同,所以答案累加n-(R-1)+1

如果对于每个L都重新计算一遍R肯定不行
尺取可以利用上一次的信息

ps:
爆int

code:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
typedef long long ll;
using namespace std;
#define int long long
const int maxm=1e6+5;
char s[maxm];
int mark[maxm];
signed main(){
    int T;
    scanf("%lld",&T);
    while(T--){
        memset(mark,0,sizeof mark);
        scanf("%s",s+1);
        int n=strlen(s+1);
        int k;
        scanf("%lld",&k);
        int ans=0;
        int l=1,r=1;
        int sum=0;
        while(1){
            while(r<=n&&sum<k){
                int v=s[r]-'a';
                mark[v]++;
                r++;
                if(mark[v]==1){
                    sum++;
                }
            }
            if(sum<k)break;
            ans+=n-(r-1)+1;
            //
            int v=s[l]-'a';//l每次右移一格
            mark[v]--;
            l++;
            if(mark[v]==0){
                sum--;
            }
        }
        printf("%lld\n",ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值