【Question】
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.【Examples】
Input1
1
1010Output1
6
Input2
2
01010Output2
4
Input3
100
01010Output3
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”.【思路】
题意:给定一个只包含1和0的串,问其中恰好包含k个1的字串的个数
话说这道题题解真的巧妙,想不到……看了半天才弄懂了
看代码,有注释
【源代码】
#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
using namespace std;
int num[1000010];
int main()
{
long long int ans=0;
int k;
cin >> k;
string s;
cin >> s;
num[0]=1;//num[i]里面存的数表示从串首开始恰好有i个1的串的个数。
int mid=0;
for(int i=0;i<s.length();i++)
{ //num[cnt-k]就是当前已经出现的1的总个数减去要求的个数,
if(s[i]=='1')
mid++;
if(mid>=k)
ans+=num[mid-k];
/*这里为什么这么写呢
在遇见下一个1之前,含第i位字串的数目就等于该位本身到前一位1的数字的个数
举个例子,1010,当在第0位时,就此一位;但i=1时,包含该位的含1的字串数目就等于1,此时ans=1+1=2
i=2时,又遇见1,mid+1后,此时看前一位1后面有几位数即字串个数;
i=3时,含该位的字串为01,010两种,即该位到前一位1的数字的数量
*/
num[mid]++;//累计第i个1后面0的个数+1本身
}
cout << ans <<endl;
}