原题链接:https://codeforces.com/contest/1186/problem/C
题意:给你两个01串a、b,问a中长度为b的子串c,与b相对应位不同的个数加起来为偶数的有多少个?
思路:既然是相对应位不同,那么会想到异或^
。两个数(也可以是字符)的异或是不同为1,相同为0。异或两次同一个数(字符),相当于没有异或这个数(字符),异或值还是0。
#include <bits/stdc++.h>
using namespace std;
int main(){
string a,b;
cin>>a;
cin>>b;
int a_len = a.length();
int b_len = b.length();
int ans = 0, num = 0;
for(int i=0;i<b_len;i++){
ans = ans ^ a[i] ^ b[i]; //异或前b_len位
}
if((ans & 1) == 0){
num ++;
}
for(int i=b_len;i<a_len;i++){ //异或b_len位后面的
ans = ans ^ a[i] ^ a[i-b_len]; //异或一个a[i-b_len]是为了消除前面异或时造成的影响。
if( !(ans & 1)){
num ++;
}
}
cout<<num<<endl;
return 0;
}