Genos needs your help. He was asked to solve the following programming problem by Saitama:
The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as , where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2.
Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.
The first line of the input contains binary string a (1 ≤ |a| ≤ 200 000).
The second line of the input contains binary string b (|a| ≤ |b| ≤ 200 000).
Both strings are guaranteed to consist of characters '0' and '1' only.
Print a single integer — the sum of Hamming distances between a and all contiguous substrings of b of length |a|.
01
00111
3
0011
0110
2
For the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3.
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<queue>
#define bug printf("***\n");
//#define mem0 memset(a, 0, sizeof(a));
using namespace std;
typedef pair<long long, int> par;
const int mod = 1e9+7;
const int INF = 1e9;
const int N = 10010;
int main()
{
char str[N], ch[N];
int pre0[N], pre1[N]; //前缀0的个数、前缀1的个数
while(~scanf("%s%s", ch, str)) {
long long ans = 0;
int len1 = strlen(ch);
int len2 = strlen(str);
pre0[0] = pre1[0] = 0;
if(str[0] == '0') pre0[0] = 1;
else pre1[0] = 1;
for(int i = 1; i < len2; i ++) { //统计前缀和
if(str[i] == '1') {
pre1[i] = pre1[i-1]+1;
pre0[i] = pre0[i-1];
}else {
pre0[i] = pre0[i-1]+1;
pre1[i] = pre1[i-1];
}
}
for(int i = 0; i < len1; i++) { //计算出匹配区间内所有不同的对数
if(i == 0) {
if(ch[i] == '0') ans += pre1[len2-len1];
else ans += pre0[len2-len1];
}else {
if(ch[i] == '0') ans += (pre1[len2-len1+i] - pre1[i-1]);
else ans += (pre0[len2-len1+i] - pre0[i-1]);
}
}
printf("%lld\n", ans);
}
return 0;
}