Problem description
Have a10\leq10≤ length\leq 1,000,000≤1,000,00 0strings, consisting only of lowercase letters. How many substrings are available, containing at least K (1 \leq k \leq)K(1≤k≤26) different letters?
Enter a description
The input contains multiple sets of data. The first line has an integert (1\leq t\leq) < Span class= "Strut bottom" >t (1≤t≤1< Span class= "Mord" >0s< Span class= "Strut bottom" >s. The second line enters an integer kk.
Output description
For each set of data, the output meets the required number of substrings.
Input sample
2abcabcabca4abcabcabcabc3
Output sample
25w
There is an obvious nature: if the substring(I,J)Contains at leastKA different character, then the substring < Span class= "Mord mathit" >k < Span class= "Mord mathit" to a different character.
So for each left boundary, as long as you find the smallest right boundary that satisfies the condition, you can be in o< Span class= "Mopen" > (1) All of the qualifying substrings starting with the left boundary are counted in time.
The
Search for this right boundary is a classic catch-up (ruler method, double-pointer) problem. Maintain two pointers (array subscript), update the left and right boundaries in turn, and accumulate the answers. Complexity o (Length (S)) < Span class= "Mopen" >
< Span class= "Mclose" >------------------------------------------------
Just like a ruler, just start left = right = 0, and then first fixed the beginning of left = 0, find the length of the ruler that satisfies the condition, then left++, modify the right length, the ruler length is unchanged, and once you add it to the back, you have to add it.
1#include <iostream>2#include <algorithm>3#include <cstdio>4#include <Set>5#include <cstring>6 using namespacestd;7typedefLong LongLL;8 Const intMax =1000000+Ten;9 CharStr[max];Ten intcnt[ -]; One intMain () A { - intT; -scanf"%d", &t); the while(t--) - { - intK, left, right; -scanf"%s", str); +scanf"%d", &k); - intLen =strlen (str); + intnum =0; Aleft = right =0; atmemset (CNT,0,sizeof(CNT)); -LL ans =0; - while(left <= Len-k) - { - while(Num < K && right < Len)//always found satisfying k different characters, i.e. the right end of a ruler - { in if(cnt[Str[right]-'a'] ==0) - { tonum++; +}//no access to only + +; -cnt[Str[right]-'a']++; theright++; * } $ if(num = = k)//the number of substrings can be counted when the number of characters = = kPanax NotoginsengAns + = Len-right +1; -cnt[Str[left]-'a']--;//the left side is going backwards, so if the number of characters in the leftmost position--and then 0--then the number of characters num is 1. the if(cnt[Str[left]-'a'] ==0) +num--; Aleft++; the } +printf"%i64d\n", ans); - } $ return 0; $}
View Code
Hdu5872string (Ruler standard method)