19集训02C题(codeforces 608B)解题报告

附原题: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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值