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.
The second sample case is described in the statement.
题意:两个只有01的字符串a,b;问a在b中连续的一段等长的字符|ai-bi|的和是多少。
分析:贴个题解吧,我也是这么想的。
We are trying to find . Swapping the sums, we see that this is equivalent to
.
![](http://codeforces.com/predownloaded/37/1f/371fb249e711d83cf5e5ba84f168c13ed1547e2b.png)
![](http://codeforces.com/predownloaded/99/4a/994a568c1c1cddfeec50d7b394f3956f2985252b.png)
![](http://codeforces.com/predownloaded/70/98/7098e4a8203a94dfab7660a362fa64b7669fda90.png)
我没注意到最后和的大小会爆int,WA了。。。。。谨记!
#include<bits/stdc++.h>
using namespace std;
#define LL long long
int main()
{
//freopen("f.txt","r",stdin);
string a,b;
cin>>a>>b;
int na=a.size(),nb=b.size();
// cout<<nb-na<<endl;
int compare=nb-na+1;
LL sum=0,ans=0;
for(int i=0;i<compare;i++)
if(b[i]=='1')sum++;
// cout<<ans<<sum<<endl;
for(int i=0;i<na;i++){
//if(b[i]==)
if(a[i]=='1') ans+=compare-sum;
else ans+=sum;
if(b[i]=='1')sum--;
if(b[i+compare]=='1')sum++;
// cout<<ans<<" "<<sum<<endl;
}
cout<<ans<<endl;
}