E - Another Problem on Strings

倖福魔咒の 提交于 2020-02-29 14:13:15

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;
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!