还是先学长的
学长原贴: https://www.cnblogs.com/xyq0220/p/12036109.html
学长思路:
在字符串s中所有不能打出的字母的位置作为隔板,隔出来的每个子串(设len为子串的长度)对答案的贡献即为len×(len+1)/2。
1 #include<bits/stdc++.h> 2 #define fi first 3 #define se second 4 #define lson l,mid,p<<1 5 #define rson mid+1,r,p<<1|1 6 #define pb push_back 7 #define ll long long 8 using namespace std; 9 const int inf=1e9; 10 const int mod=1e9+7; 11 const int maxn=2e5+10; 12 int n,k; 13 char s[maxn],t[30]; 14 int main(){ 15 ios::sync_with_stdio(false); 16 //freopen("in","r",stdin); 17 cin>>n>>k; 18 cin>>s+1; 19 for(int i=1;i<=k;i++){ 20 char c; 21 cin>>c; 22 t[c-'a']=1; 23 } 24 ll ans=0,cnt=0; 25 for(int i=1;i<=n;i++){ 26 if(!t[s[i]-'a']){ 27 ans+=cnt*(cnt+1)/2; 28 cnt=0; 29 }else ++cnt; 30 } 31 ans+=cnt*(cnt+1)/2; 32 cout<<ans<<endl; 33 return 0; 34 }
我的代码:
1 #include <bits/stdc++.h> 2 using namespace std; 3 int main(){ 4 long long int n,temp=0,k,biao[26],count=0; 5 long long int sum =0; 6 char str[200005],tc; 7 memset(biao,0,sizeof(biao)); 8 memset(str,'\0',sizeof(str)); 9 cin>>n>>k; 10 temp = n; 11 cin>>str; 12 while(k--){ 13 cin>>tc; 14 biao[tc-'a'] = 1; 15 } 16 for(int i = 0;i<n;i++){ 17 if(biao[str[i]-'a']){ 18 count += 1; 19 } 20 else{ 21 sum += count*(count+1)/2; 22 count = 0; 23 } 24 } 25 sum += count*(count+1)/2; 26 cout<<sum<<endl; 27 return 0; 28 }
其实这题又和学长思路一样,把缺的字母当隔板,对每个隔间累加求总值。
可能是这题比较简单(但是比赛我就蒙了???),所以代码差别不大
都用了标记法,这也是这种题的常用手法。