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 is1 + 0 + 1 + 1 = 3.
The second sample case is described in the statement.
题意:输入两个只包含1和0的字符串a,b(1≤|a| ≤ |b| ≤ 200 000)。a与b中所有相等长度的连续子串进行比较,结果为每位数差的绝对值之和。输出所有结果的和。
样例1:a是01,b是00111;01与00(b中的第1位和第2位)比较,01与01(b中的第2位和第3位)比较,01与11(b中的第3位和第4位)比较,01与11(b中的第4位和第5位)比较。每一个比较的结果分别为1,0,1,1。输出结果的和3。
思路分析:a中的第1个数要和b中的第1,2,3,4个数进行比较,a中的第2个数要和b中的第2,3,4,5个数进行比较。a中的每一个数都比较了4次,设字符串a的长度为lena,b的长度为lenb,那就是要比较compare=lenb-lena+1次。每一次比较只要统计当前区间 [ b[i],b[i+compare])b为1的个数sum,如果a[i]=1,就加上compare-sum;如果a[i]=0,就加上sum。第一次sum的值就是for(i=0;i<compare;i++) if(b[i]==1) sum++;以后每次比较完之后就只要if(b[i]==1) sum--;if(b[i+compare]==1) sum++;
#include<iostream> #include<cstdio> using namespace std; int main() { string a,b; int na,nb,compare; cin>>a>>b; na=a.size(); nb=b.size(); compare=nb-na+1; int i; __int64 sum=0,ans=0; for(i=0; i<compare; i++) if(b[i]=='1')sum++; for(i=0; i<na; i++) { if(a[i]=='1') ans+=compare-sum; else ans+=sum; if(b[i]=='1')sum--; if(b[i+compare]=='1')sum++; } cout<<ans<<endl; }