C - Yet Another Broken Keyboard

题意:给你一串只含小写字母字符串,和几个可用字母,求用所给字母能表示所给字符串中的子串数量。

思路:题中已给出(n个字符的)子串和该子串能分解出多少子串的数量关系:n*(n+1)/2。所以找出每一段子串,求该段子串能分成多少子子串,求出数量之和即可。

特别注意要用long long int,否则会超出范围。

#include<stdio.h>
#include<string.h>
int main(){
        long long int n,k,i,j,s,sum,t,flag;
        char a[int(1e6)],b[30];
        while(~scanf("%lld %lld%*c",&n,&k)){
                gets(a);
                for(i=0;i<k;i++)
                        scanf("%s",&b[i]);
                for(i=flag=sum=t=0;i<n;i++){
                        for(j=0,flag=0;j<k;j++){
                                if(a[i]==b[j]){
                                        sum++;
                                        flag=1;
                                        break;
                                }
                        }
                        if(flag==0){
                                t=t+(sum*(sum+1)/2);
                                sum=0;
                        }
                }
                if(flag==1)
                        t=t+(sum*(sum+1)/2);
                printf("%lld\n",t);
        }
}
View Code

猜你喜欢

转载自www.cnblogs.com/DreamingBetter/p/12189344.html