2019/12/12 CF-1272-C Yet Another Broken Keyboard

Codeforces Round #605 (Div. 3)

题目链接:http://codeforces.com/contest/1272/problem/C

题意大意:

        若第一个字符串中的字符出现在第二个字符串中,说明该字符有效。找出第一个字符串中连续有效字符串子串个数。

n个字符有n*(n-1)/2个子串。

思路:

        cnt从0开始计数,当s[i]有效时cnt++,当s[i]无效时开始计算cnt个有效字符子串,然后cnt重置为0,最后别忘了加上最后一组cnt个有效字符的子串个数。

测试样例:

input
7 2
abacaba
a b
output
12

input
10 3
sadfaasdda
f a d
output
21

inputC
7 1
aaaaaaa
b
output
0

AC代码1:

#include<bits/stdc++.h>
using namespace std;
const int maxn=2*1e5+5;
char s1[maxn],s2[30];
int main()
{
    int x,y;
    scanf("%d%d",&x,&y);
    scanf("%s",s1);
    int len=strlen(s1);
    for(int i=0;i<y;i++)
        scanf(" %c",&s2[i]);
    int j;
    long long sum=0,cnt=0;
    for(int i=0;i<len;i++)
    {
        for(j=0;j<y;j++)
            if(s1[i]==s2[j])
            {
                cnt++;
                break;
            }
        if(j==y)
        {
            sum+=cnt*(cnt+1)/2;
            cnt=0;
        }

    }
    printf("%lld\n",sum+cnt*(cnt+1)/2);//注意最后一组不要忘了
    return 0;
}

AC代码2:

#include<bits/stdc++.h>
using namespace std;
const int maxn=2*1e5+5;
char s1[maxn],s2[30];
bool vis[27];
int main()
{
    int x,y;
    scanf("%d%d",&x,&y);
    scanf("%s",s1);
    for(int i=0;i<y;i++)
    {
        scanf(" %c",&s2[i]);
        vis[s2[i]-65]=true;
    }
    long long sum=0,cnt=0;
    for(int i=0;i<x;i++)
    {
        if(vis[s1[i]-65])
            cnt++;
        else
        {
            sum+=cnt*(cnt+1)/2;
            cnt=0;
        }
    }
    printf("%lld\n",sum+cnt*(cnt+1)/2);

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值