B. Hamming Distance Sum(思维)

传送门

  • 题意:定义两个串的哈夫曼距离距离为 123
    现在给定两个01串a,b(|a| <= |b|),求出a串与b的所有子串(连续的子串)的哈夫曼距离之和。
  • 思路:设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>
#define endl "\n"
#define IOS ios::sync_with_stdio(0), cin.tie(0),cout.tie(0)
#define ft first
#define sd second
#define pll pair<ll, ll>
#define pii pair<int, int>
#define ll long long int
#define mt(a,b) memset(a, b, sizeof a)
//#define int long long
const int inf = 0x3f3f3f3f;
const int INF = 0x7fffffff;
using namespace std;
const int N = 2e5 + 7, M = 1e6;
ll num[N];
int main()
{
	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;

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

to cling

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值