hdu 5672 尺取法模拟

来源:互联网 发布:质量数据的统计方法 编辑:程序博客网 时间:2024/04/30 03:36

题目:

String

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


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 integer T(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 least k dictinct characters.
 

Sample Input
2abcabcabca4abcabcabcabc3
 

Sample Output
055

给一个仅由小写字母串 和整数K 问这个串有多少个子串中不同字母的个数>=k


思路:

枚举左端点 尺取法找到最左的右端点使得左右端点组成的区间覆盖所有出现过的字母


代码:

自己写的

#include<set>#include<map>#include<cstdio>#include<cstring>#include<iostream>using namespace std;const int maxn=1000010;string s;int as[maxn];int t,k;long long ans;///wa的原因....爆intint m[30];///使用map来判断是否出现过会超时int main(){    ios_base::sync_with_stdio(false);    cin>>t;    while(t--){        cin>>s>>k;        int len=s.length();        for(int i=0;i<len;++i) as[i]=(s[i]-'a');        ans=0;        memset(m,0,sizeof(m));        int l=0,r=0,cnt=0;        while(1){            while(r<len&&cnt<k){                if(!m[as[r]]) cnt++;                m[as[r]]++; r++;            }            int cc=1;            while(m[as[l]]>1) m[as[l++]]--,++cc;///一个小优化 没有这一行下面就得加if(!m[as[l-1]])            ///加上这一句就意味着往ans里面加的时候 这个可行区间的左端点一定在这个区间中只出现了一次            ///下面左指针前移时就可以直接cnt--了 参考样例ababcc 3 输出6 一次就加好了            if(cnt==k){                //cout<<l<<"  "<<r<<"  "<<cc<<endl;                ans+=(len+1-r)*cc;                cout<<"ans+="<<(len+1-r)<<endl;                m[as[l++]]--;///l++相当于枚举左端点                /*if(!m[as[l-1]])*/ cnt--;            }            else break;///走到头啦        }        cout<<ans<<endl;    }    return 0;}

disscuss中别人的:

#include<bits/stdc++.h>using namespace std;const int maxn=1000008;char s[maxn];int main(){    int t,tt;    for(scanf("%d",&t); t--;)    {        scanf("%s",s);        scanf("%d",&tt);        int cnt[26];        int len=strlen(s),kk=0;        long long sum=0;        memset(cnt,0,sizeof(cnt));        int l=0,r=0;        while(l<=r)        {            while(kk<tt&&r<len)            {                if(!cnt[s[r]-'a']) kk++;                cnt[s[r]-'a']++;                r++;            }            if(kk==tt) sum+=len-r+1;            else break;            cnt[s[l]-'a']--;            if(!cnt[s[l]-'a']) kk--;            l++;        }        printf("%I64d\n",sum);    }}





原创粉丝点击