Codeforces Round #336 (Div. 2)B. Hamming Distance Sum 前缀和
B. Hamming Distance Sum
题目连接:
http://www.codeforces.com/contest/608/problem/A
Description
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|.
Input
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.
Output
Print a single integer — the sum of Hamming distances between a and all contiguous substrings of b of length |a|.
Sample Input
01
00111
Sample Output
3
Hint
题意
给你一个a串,和一个b串,让A串去依次匹配b[0]-b[lena-1],b[1]-b[lena],b[2]-b[lena+].....
然后权值就是上下相减的绝对值
问你最后的权值和是多少
题解:
记录B串的前缀和,对于A串的每个字母而言,他所花费的代价,就是他移动的区间中,和他不一样的数的个数就好了
直接扫一遍就OK
代码
#include<bits/stdc++.h>
using namespace std;
#define maxn 200005
long long sum[maxn][2];
char a[maxn],b[maxn];
int A[maxn],B[maxn];
int main()
{
scanf("%s%s",a+1,b+1);
int len = strlen(a+1),len2 = strlen(b+1);
for(int i=1;i<=len;i++)
A[i]=a[i]-'0';
for(int i=1;i<=len2;i++)
B[i]=b[i]-'0';
for(int i=1;i<=len2;i++)
{
for(int j=0;j<2;j++)
sum[i][j]+=sum[i-1][j];
sum[i][B[i]]++;
}
long long ans = 0;
for(int i=1;i<=len;i++)
{
ans+=sum[len2-len+i][1-A[i]];
ans-=sum[i-1][1-A[i]];
}
cout<<ans<<endl;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· .NET 进程 stackoverflow异常后,还可以接收 TCP 连接请求吗?
· SQL Server统计信息更新会被阻塞或引起会话阻塞吗?
· C# 深度学习框架 TorchSharp 原生训练模型和图像识别
· 这或许是全网最全的 DeepSeek 使用指南,95% 的人都不知道的使用技巧(建议收藏)
· 拒绝繁忙!免费使用 deepseek-r1:671B 参数满血模型
· 本地搭建DeepSeek和知识库 Dify做智能体Agent(推荐)
· Sdcb Chats 重磅更新:深度集成 DeepSeek-R1,思维链让 AI 更透明!
· DeepSeek-R1本地部署如何选择适合你的版本?看这里