E - Another Problem on Strings

A string is binary, if it consists only of characters “0” and “1”.

String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string “010” has six substrings: “0”, “1”, “0”, “01”, “10”, “010”. Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.

You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters “1”.

Input
The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.

Output
Print the single number — the number of substrings of the given string, containing exactly k characters “1”.

Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
暴力搜搜

#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char b[1000001];
int main()
{
    int n;
    cin>>n;
    scanf("%s",b+1);
    int len=strlen(b+1);
    long long k=0;
    long long d=0;
    if(n==0)
    {
        for(int i=1;i<=len;i++)
        {
            if(b[i]=='0') k++;
            else {d=d+((k+1)*k)/2;k=0;}
        }
        d=d+((k+1)*k)/2;
        cout<<d<<endl;
        return 0;
    }
    int p=n;
    while(p<=len)
    {
        for(int i=0;i<=len;i++)
        {
            if(i+p<=len)
            {
                 for(int j=i+1;j<=i+p;j++)
            {
                if(b[j]=='1')
                    k++;
            }
            if(k==n){ d++; k=0;}
            else k=0;
            }
        }
        p++;
    }
    cout<<d<<endl;
    return 0;
}

这样弊端是搜索次数过多,严重浪费。
哎,然后找了一下题解,恍然大悟。
然后这题从前往后找一有前瞻后连的性质
笔画一下1000001001110000,找有一个1的情况,发现一与以后的零有关系,可以吧每次符合条件的那个的序号对应一个状态值 ,就是当前的符合条件的个数,符合条件的那个前面每多一个零就多一种情况。然后f[i-k] 就好像行了。
这个的初始条件不好弄,可以笔画100100100111111 和0101011111 的情况来定一下。

#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n;
char b[1000001];
int f[1000001];
int main()
{
    int n;
    cin>>n;
    scanf("%s",b+1);
    int len=strlen(b+1);
    int op=0;
    long long ans=0;
    f[0]=1;
    for(int i=1;i<=len;i++)
    {
        if(b[i]=='1') op++;
            if(op>=n) ans=ans+f[op-n];
            f[op]++;
    }
    cout<<ans<<endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值