附原题:Hamming Distance Sum
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|.
题意:给两个01串a和b,求b串中所有连续的与a串等长的子串与a串的距离。01串间的距离是指对应字符差值的绝对值之和。
(比如:"0011"和"0110"的距离是|0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2.)
解题思路:假如用最暴力的方法肯定是一位一位的比较。这样肯定会超时。
假如分散到每一位上,就是a[i]先要和b[i]求距离,然后和b[i+1]求距离...以此类推
那就可以把问题转化成a[i]和b[i]~b[i+l2-l1]这一串字符距离的差值。
所以我们用前缀和统计b[i]中0和1的个数,然后如果a[i]==0,就把b串对应段的1的个数加到总数上就可以了,a[i]==1同理。
附代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int MAXN=2e5+5;
char s1[MAXN],s2[MAXN];
ll a[MAXN],b[MAXN],cnt;
int main(){
while (cin>>(s1+1)>>(s2+1)){
ll l1=strlen(s1+1),l2=strlen(s2+1);cnt=0;
a[0]=b[0]=0;
for (int i=1;i<=l2;i++){
if (s2[i]=='1') a[i]=a[i-1]+1,b[i]=b[i-1];
else a[i]=a[i-1],b[i]=b[i-1]+1;
}
for (int i=1;i<=l1;i++){
if (s1[i]=='1') cnt+=b[l2-l1+i]-b[i-1];
else cnt+=a[l2-l1+i]-a[i-1];
}
cout<<cnt<<endl;
}
return 0;
}