HDU-5672-String(模拟/追赶)

来源:互联网 发布:node in action中文版 编辑:程序博客网 时间:2024/06/06 02:24

String

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 918    Accepted Submission(s): 295


Problem Description
There is a string S.S only contain lower case English character.(10length(S)1,000,000)
How many substrings there are that contain at least k(1k26) distinct characters?
 

Input
There are multiple test cases. The first line of input contains an integerT(1T10) indicating the number of test cases. For each test case:

The first line contains string S.
The second line contains a integer k(1k26).
 

Output
For each test case, output the number of substrings that contain at leastk dictinct characters.
 

Sample Input
2abcabcabca4abcabcabcabc3
 

Sample Output
055
 

Source
BestCoder Round #81 (div.2)
 


String

有一个明显的性质:如果子串(i,j)(i,j)(i,j)包含了至少kkk个不同的字符,那么子串(i,k),(j<k<length)(i,k),(j < k < length)(i,k),(j<k<length)也包含了至少kkk个不同字符。

因此对于每一个左边界,只要找到最小的满足条件的右边界,就能在O(1)O(1)O(1)时间内统计完所有以这个左边界开始的符合条件的子串。

寻找这个右边界,是经典的追赶法(尺取法,双指针法)问题。维护两个指针(数组下标),轮流更新左右边界,同时累加答案即可。复杂度 O(length(S))



#include <iostream>#include <cstdio>#include <vector>#include <algorithm>#include <cstring>#include <string>#include <cmath>#include <set>#include <map>#include <queue>#include <stack>using namespace std;#define MAXN 1000005char str[MAXN];long long num[30];int main(){    int T;    scanf("%d",&T);    while(T--)    {        scanf("%s",str+1);        long long len = strlen(str+1);        long long n;        scanf("%I64d",&n);        long long l=1,r=0,tot=0,ans=0;        for(int i=0; i<26; ++i)            num[i]=0;        while(1)        {            if(tot<n && r<len)            {                int x = str[++r]-'a';                if(num[x]==0)++tot;                num[x]++;            }            else if(n<=tot)            {                ans+=len-r+1;                int x = str[l++]-'a';                num[x]--;                if(num[x]==0)--tot;            }            else break;        }        printf("%I64d\n",ans);    }    return 0;}



0 0