Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2370 Accepted Submission(s): 780
Problem Description
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?
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) .
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
Source
Recommend
求包含不同字母数不小于k的子串数。尺取法,两个下标移动,当tail移动到head~tail包含了k个不同的字母时,ans就加len - tail + 1,加上后面的字母组成的子串满足条件,然后移动head,每次移动ans都加len - tail + 1,直到head~tail包含不同的字母不足k时再次移动tail。
代码:
#include <iostream> #include <cstdio> #include <cstring> #define inf 0x3f3f3f3f #define MAX 302 using namespace std; int main() { int t,k,v[30]; char s[1000005]; scanf("%d",&t); while(t --) { scanf("%s%d",s,&k); long long ans = 0; int len = strlen(s); int c = 0; memset(v,0,sizeof(v)); int head = 0,tail = 0; while(tail < len) { int d = s[tail ++] - 'a'; if(!v[d]) c ++; v[d] ++; if(c >= k) { while(head <= tail) { int e = s[head ++] - 'a'; v[e] --; ans += len - tail + 1; if(!v[e]) { c --; break; } } } } printf("%lld ",ans); } }