题目如下:
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
思路:直观的看来,可以想到这道题就是不停比较两个串不同字符个数,然后会发现这样做时间复杂度至少是O(N^2),会超时。
实际上,我们可以换一个思路:首先,有一个字符串是需要不停地去比较的,那么,我们可以这样考虑,看看这个串中每一位分别与那些位比较过了。其次,由于只有0和1,那么如果是看0比较过的位置,只需要计算出1的个数就可以了,反之亦然。最后,我们发现比较的位置是连续的,这个用部分和进行优化可以得到很好的效果。这样,线性时间就可以解决了。
代码如下:
#include <iostream>
using namespace std;
const int maxn = 1e5+3;
long long q0[maxn*2],q1[maxn*2];
int main(int argc, const char * argv[]) {
string s1,s2;
cin >> s1 >> s2;
q0[0]=0;q1[0]=0;
for (int i=0; i<s2.length(); i++) {//计算部分和,即统计0和1的个数分别是多少
q0[i+1]=q0[i];q1[i+1]=q1[i];
if (s2[i]=='0') q0[i+1]++;else q1[i+1]++;
}
int l1 = s1.length();
int l2 = s2.length();
long long ans = 0;
for (int i=0; i<l1; i++) {//计算串1每个位置与串2比较时,有多少个不同
if (s1[i] == '0') {
ans += q1[l2-l1+i+1]-q1[i];
}else ans += q0[l2-l1+i+1]-q0[i];
}
cout << ans;
return 0;
}