Another Problem on Strings CodeForces - 165C

Another Problem on Strings

CodeForces - 165C

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.

Example
Input
1
1010
Output
6
Input
2
01010
Output
4
Input
100
01010
Output
0
Note

In the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".

In the second sample the sought substrings are: "101", "0101", "1010", "01010".

这道题一开始不会做,在网上看到一种很巧妙的方法。

code:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int num[10000000];//num[i]实际上代表的是第i个1后面跟了几个0的个数+1(加1就是加上1字符本身也算一个),例如num[1] = 2            就代表第一个1后面有一个0加上1本身,所以num[1]为2,之后是第二个1
char s[10000000];//存字符串
int main(){
    int k;
    cin >> k >> s;
    long long ans = 0;
    int cnt = 0;//cnt代表第cnt个1,每次遇到新的1,cnt++
    int len = strlen(s);
    int i;
    memset(num,0,sizeof(num));
    num[0] = 1;
    for(i = 0; i < len; i++){//一位一位进行遍历
        if(s[i] == '1')cnt++;
        if(cnt >= k)ans += num[cnt-k];
        
        //当出现的1的个数大于等于要求的k了,就开始计算了
        //num[cnt-k]就是当前已经出现的1的总个数减去要求的个数,也就是固定有k个1的字符串长度后,往前在到达第k+1个1之  间0的个数就是包含这k个1的字符串所能构成的子串。
       //举个例子。k = 2时若串是00100101,假设到了最后一个1也就是第三个1,cnt=3>k=2,所以此时得到num[cnt-k] = num[1],num[1]是记录1后面的0个数+1,这样也就是我固定了后两个1即固定了串101,往前找,在第一个1之前有几个零是不是就可以有几种子串,当然还要加上不加0的它本身,这也是num[i]数组加1,num[0]初始化1的用意。      
       
        num[cnt]++;//储存第cnt个1后面0的个数加上1这个本身
    }
    cout << ans << endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值