• 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;
    }
  • 相关阅读:
    面向对象(二)-特性
    面向对象(一)-初步认识
    函数(十)-内置模块
    函数(九)-包与模块
    函数(八)-闭包与装饰器
    函数(七)-嵌套作用域
    函数(六)-匿名函数
    CSS阴影效果(Box-shadow)用法趣味讲解
    css 实现div内显示两行或三行,超出部分用省略号显示
    js基础知识(一)--截取字符串
  • 原文地址:https://www.cnblogs.com/qscqesze/p/5075236.html
Copyright © 2020-2023  润新知