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".
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.
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.
1 1010
6
2 01010
4
100 01010
0
In the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".
In the second sample the sought substrings are: "101", "0101", "101""01010".
/*
3 00000100101000100 31+1+1
思路整体明确了嗯就是说 把一之前的0球出来1后面的0也求出来
这样子一共就有本身没有前后0+前后有零的个数再加上前后0相乘的个数
累加就行
其中出现wa的就是当K=0的时候没有考虑到这边wa了好几发
嘻嘻~~~~开心,昨天想说自己应该写不出来于是尝试都没有尝试~~下次要勇于尝试
*/
代码:
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
char str[1111111];
int main()
{
int k;
scanf("%d %s",&k,str);
long long sum=0;
int cnt=0,first=0,last=0,temp,flag=0;
int len=strlen(str);
if(k==0)
{
for(int i=0;i<len;i++)
{
if(str[i]=='0')
{
cnt++;
flag=0;
}else
{
if(flag)continue;
sum=sum+cnt*(cnt+1)/2;
cnt=0;
flag=1;
}
}
sum+=(str[len-1]-'0'==0)?cnt*(cnt+1)/2:0;
printf("%lld\n",sum);
return 0;
}
for(int i=0;i<len;i++)
{
if(str[i]=='1')cnt++;
if(cnt==1&&!flag)
{
temp=i;
flag=1;
}
if(cnt==k)
{
int j=i;
i=temp;
temp--;
while(temp>=0&&str[temp]=='0' )
{
first++;
temp--;
}
j++;
while(j<len&&str[j]=='0')
{
last++;
j++;
}
sum=sum+1+first+last+first*last;
cnt=0,first=last=0;
flag=0;
}
}
printf("%lld\n",sum);
return 0;
}