C. Equalize
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given two binary strings a and b of the same length. You can perform the following two operations on the string a Swap any two bits at indices i and j respectively (1≤i,j≤n), the cost of this operation is |i−j|, that is, the absolute difference between i and j Select any arbitrary index i
(1≤i≤n) and flip (change 0 to 1 or 1 to 0) the bit at this index. The cost of this operation is 1 Find the minimum cost to make the string a equal to b. It is not allowed to modify string b
.
Input
The first line contains a single integer n
(1≤n≤106) — the length of the strings a and bThe second and third lines contain strings a and b respectively.Both strings a and b have length n and contain only ‘0’ and ‘1’.
Output
Output the minimum cost to make the string a
equal to b
Examples
Input
Copy
3
100
001
Output
Copy
2
Input
Copy
4
0101
0011
Output
Copy
1
Note
In the first example, one of the optimal solutions is to flip index 1
and index 3, the string a changes in the following way: “100” → “000” → “001”. The cost is 1+1=2The other optimal solution is to swap bits and indices 1
and 3, the string a changes then “100” → “001”, the cost is also |1−3|=2
In the second example, the optimal solution is to swap bits at indices 2
and 3, the string a changes as “0101” → “0011”. The cost is |2−3|=1
题目:Equalize
题意:
给出两个长度相等的01串,求把其中一种变成另一种的最下代价。
操作1:交换两个位置在i,j的数,代价是|i−j|。
操作2:把一个数异或1,代价为1
。
思路:
首先可以知道,使用操作1
时,只能交换相邻两元素。因为如果交换的两元素距离大于1,那么使用操作2一定更优。
然后令f[i]表示前i个数的最小代价。
当a[i]==b[i]时,f[i]=f[i−1]。
当a[i]!=b[i]时,若(a[i−1]==b[i] and a[i]==b[i−1] and !g[i−1])==0,f[i]=f[i−1]+1。
其中g代表是否在i处做过操作1。
#include<bits/stdc++.h>
using namespace std;
#define maxn 1000000
#define inf (1<<30)
int n;
void read(int& x) {
char y;
while(~scanf("%c",&y)&&(y<'0'||y>'1'));
x=y-'0';
}
int a[maxn+5],b[maxn+5];
int f[maxn+5],g[maxn+5];
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++) read(a[i]);
for(int i=1;i<=n;i++) read(b[i]);
for(int i=1;i<=n;i++) {
f[i]=f[i-1];
if(a[i]!=b[i]) {
if(a[i-1]==b[i]&&a[i]==b[i-1]&&!g[i-1]) g[i]=true;
else f[i]++;
}
}
printf("%d",f[n]);
return 0;
}