Codeforces Round #336 (Div. 2) B 暴力

CrossDolphin發表於2016-07-08



連結:戳這裡


B. Hamming Distance Sum
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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|.

Examples
input
01
00111
output
3
input
0011
0110
output
2
Note
For the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3.

The second sample case is described in the statement.


題意:

給出兩串01串s,p 要求p中所有長度為len(s)的串與s串相減絕對值,然後累加起來並輸出


思路:

嗯 維護一下字首和然後算貢獻


程式碼:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include <ctime>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<iomanip>
#include<cmath>
#define mst(ss,b) memset((ss),(b),sizeof(ss))
#define maxn 0x3f3f3f3f
#define MAX 1000100
///#pragma comment(linker, "/STACK:102400000,102400000")
typedef long long ll;
typedef unsigned long long ull;
#define INF (1ll<<60)-1
using namespace std;
string s,p;
int sum[200100];
int a[200100];
int b[200100];
int main(){
    cin>>s>>p;
    int n=s.size(),m=p.size();
    for(int i=1;i<=n;i++){
        b[i]=s[i-1]-'0';
        b[i]*=(m-n+1);
    }
    sum[0]=0;
    for(int i=1;i<=m;i++){
        int a=p[i-1]-'0';
        sum[i]=sum[i-1]+a;
    }
    int cnt=0;
    for(int i=m-n+1;i<=m;i++){
        a[++cnt]=sum[i]-sum[i-(m-n+1)];
    }
    ll ans=0;
    for(int i=1;i<=n;i++){
        ans+=abs(b[i]-a[i]);
    }
    cout<<ans<<endl;
    return 0;
}
/*
1001101001101110101101000
01111000010011111111110010001101000100011110101111
*/


相關文章