CodeForces 165 C.Another Problem on Strings(尺取)

Description

给出一个 01 01 串,问该串的恰有 k k 1的子串数量,两个子串只要在该串中位置不同则视为不同

Input

第一行一整数 k k ,之后输入一个01 s(1k,|s|106) s ( 1 ≤ k , | s | ≤ 10 6 )

Output

输出满足条件的子串数

Sample Input

1
1010

Sample Output

6

Solution

k=0 k = 0 时,统计该串连续 0 0 的个数即可,k0时,尺取,找到 k k 1后,假设右端点后面还有连续 R R 0,左端点后还有连续 L L 0,那么对答案的贡献即为 (L+1)(R+1) ( L + 1 ) ⋅ ( R + 1 )

Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=1000005;
int k,pos[maxn];
char s[maxn];
int main()
{
    scanf("%d%s",&k,s+1);
    int n=strlen(s+1);
    ll ans=0;
    if(k==0)
    {
        for(int i=1;i<=n;i++)
            if(s[i]=='0')
            {
                int num=1;
                while(i<n&&s[i]==s[i+1])i++,num++;
                ans+=(ll)num*(num+1)/2;
            }
    }
    else
    {
        int l=1,r=1,num=0;
        while(l<=n)
        {
            while(num<k&&r<=n)
            {
                if(s[r]=='1')num++;
                r++;
            }   
            if(num<k)break;
            //printf("l=%d r=%d\n",l,r);
            int L=1;
            while(l<=n&&s[l]=='0')l++,L++;
            int R=1;
            while(r<=n&&s[r]=='0')r++,R++;
            //printf("L=%d R=%d\n",L,R);
            ans+=(ll)L*R;
            if(l>n||r>n)break;
            l++,num--;
        }
    }
    printf("%I64d\n",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值