Another Problem on Strings
CodeForces - 165CA 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", "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;
}