思路:设a和b的长度分别n和m。直接暴力的话是O(n2)算法,肯定不行。所以需要降低复杂度。可以分别考虑a串中每个字符对于答案的贡献度。提到这里顺便提一下是利用前缀和思想。若还想不明白,就再提示一下。设a中第i个字母的下标为i(从1开始),则第i个字符的贡献度为 a[i]分别与b中第i个字符到第n - m + i个字符的差求和。具体看代码。
#include<cstdio>#include<queue>#include<set>#include<cstdlib>#include<string.h>#include<string>#include<iostream>#include<cmath>#include<map>#include<algorithm>#defineendl"\n"#defineIOSios::sync_with_stdio(0), cin.tie(0),cout.tie(0)#defineftfirst#definesdsecond#definepllpair<ll, ll>#definepiipair<int,int>#definelllonglongint#definemt(a,b)memset(a, b,sizeof a)//#define int long longconstint inf =0x3f3f3f3f;constint INF =0x7fffffff;usingnamespace std;constint N =2e5+7, M =1e6;
ll num[N];intmain(){
IOS;
string a, b;
cin >> a >> b;
ll sum =0;//注意,结果会爆int
ll n = a.size(), m = b.size();
a =" "+ a; b =" "+ b;//下标从1开始,便于做前缀和处理for(int i =1; i <= m; i++)//b前缀和,也即1的个数if(b[i]=='1') num[i]= num[i -1]+1;else num[i]= num[i -1];for(int i =1; i <= n; i++){//若为前者1则是后者中0的个数if(a[i]=='1') sum += m - n +1-(num[i + m - n]- num[i -1]);else sum += num[i + m - n]- num[i -1];//若为0,则为1的个数。}
cout << sum << endl;return0;}