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;
}