HDU-5672 String(尺取法)

题意

给定一个只有小写字母字符串 S ,求存在多少个子串至少包含了 k 种子母。
1 l e n g t h ( S ) 1000000

思路

开一个 c n t 数组记录此时每种字母出现的次数,并用 c u r 实时记录不同字母的个数。如果右移使此字母的 c n t 值由零变成一, c u r 值就加一;如果左移使此字母的 c n t 值由一变成零, c u r 值就减一。右移至 c u r k 时累计答案。

代码

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define FOR(i,x,y) for(int i=(x);i<=(y);i++)
#define DOR(i,x,y) for(int i=(x);i>=(y);i--)
typedef long long LL;
using namespace std;
char str[1000003];
int cnt[28];

int main()
{
    int T,k;
    scanf("%d",&T);
    while(T--)
    {
        memset(cnt,0,sizeof(cnt));
        scanf("%s%d",str+1,&k);
        int n=strlen(str+1),R=0,cur=0;
        LL ans=0;
        FOR(L,1,n)
        {
            while(L>R||R<n&&cur<k)
            {
                if(cnt[str[++R]-'a']==0)cur++;
                cnt[str[R]-'a']++;
            }
            if(R>n)break;
            if(cur>=k)ans+=n-R+1;
            cnt[str[L]-'a']--;
            if(cnt[str[L]-'a']==0)cur--;
        }
        printf("%lld\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/paulliant/article/details/80866982