You are given a string S consisting of lowercase letters, and your task is counting the number of substring that the number of each lowercase letter in the substring is no more than K.
Input
In the first line there is an integer T , indicates the number of test cases.
For each case, the first line contains a string which only consist of lowercase letters. The second line contains an integer K.
[Technical Specification]
1<=T<= 100
1 <= the length of S <= 100000
1 <= K <= 100000
Output
For each case, output a line contains the answer.
Sample Input
3
abc
1
abcabc
1
abcabc
2
Sample Output
6
15
21
题意:输入字符串, 和一个k, 计数子串中有多少个子串的每种字母重复次数不超过k次。
题解:尺取法, 尺取终点为最后一个字母重复次数为k + 1时, 此时用公式n * (n + 1) / 2可直接计算出当前所得的到子串数量, 然后前推尺子的起点, 直到最后一个字母出现次数为k。不过要注意在后边用公式计数时会有重复计算。可以用一个变量记录上次尺子的终点, 用后来这次尺子的起点, 剪掉重复部分的子串总数即可。
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll vis[30] = {0};
int main()
{
//printf("%lld\n",&a);
ll i, j, n, t, k, m;
long long ans;
scanf("%lld", &t);
while(t--){
memset(vis,0,sizeof(vis));
ans = 0;
string a;
char ch = 'z' + 2;
cin >> a;
a += ch;
scanf("%lld", &k);
ll s = 0, e = -1, ls = -1, le = -1;
for(i = 0;i < a.length();i++){
ll q = a[i] - 'a';
vis[q]++;
e++;
//cout<<q<<" "<<s<<" "<<e<<" "<<le<<endl;
if(vis[q] > k)
{
if(le < s)
ans += ((e - s) * (e - s + 1) / 2);
else
ans += ((e - s) * (e - s + 1) / 2 - (le - s + 1) * (le - s + 2) / 2);
le = e - 1;
//cout<<ans<<endl;
//cout<<"up:"<<le<<endl;
while(1){
ll qq = a[s] - 'a';
vis[qq]--;
s++;
if(vis[qq] == k)
break;
}
}
else if(i == a.length() - 1){
if(le < s)
ans += ((e - s) * (e - s + 1) / 2);
else
ans += ((e - s) * (e - s + 1) / 2 - (le - s + 1) * (le - s + 2) / 2);
break;
}
}
printf("%lld\n", ans);
}
return 0;
}
比赛时爆了int没有发现。太难受了