mission(s): 194 Accepted Submission(s): 78
Problem Description 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
Source BestCoder Round #11 (Div. 2)
意解:贪心,运用字符串的子串的前缀和技巧,和维护当前字母如果当前的字母不符合条件,则一一减去;
AC代码:
#include
#include
#include
#include
using namespace std; typedef long long ll; const int M = 1e5 + 100; vector
dp[30]; char s[M]; int k; void solve() { int p = -1; ll ans = 0; for(int i = 0; i < 26; i++) dp[i].clear(); scanf("%s %d",s,&k); for(int i = 0; s[i]; i++) { int u = (int)(s[i] - 'a'); dp[u].push_back(i); if(dp[u].size() > k) { p = max(p,dp[u][dp[u].size() - k - 1]); } ans += (i - p); } printf("%I64d\n",ans); } int main() { int T; scanf("%d",&T); while(T--) { solve(); } return 0; }