You are given two binary strings aa and bb of the same length. You can perform the following two operations on the string aa:
- Swap any two bits at indices ii and jj respectively (1≤i,j≤n1≤i,j≤n), the cost of this operation is |i−j||i−j|, that is, the absolute difference between ii and jj.
- Select any arbitrary index ii (1≤i≤n1≤i≤n) and flip (change 00 to 11 or 11 to 00) the bit at this index. The cost of this operation is 11.
Find the minimum cost to make the string aa equal to bb. It is not allowed to modify string bb.
The first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of the strings aa and bb.
The second and third lines contain strings aa and bb respectively.
Both strings aa and bb have length nn and contain only '0' and '1'.
Output the minimum cost to make the string aa equal to bb.
3
100
001
2
4
0101
0011
1
In the first example, one of the optimal solutions is to flip index 11 and index 33, the string aa changes in the following way: "100" →→ "000" →→"001". The cost is 1+1=21+1=2.
The other optimal solution is to swap bits and indices 11 and 33, the string aa changes then "100" →→ "001", the cost is also |1−3|=2|1−3|=2.
In the second example, the optimal solution is to swap bits at indices 22 and 33, the string aa changes as "0101" →→ "0011". The cost is |2−3|=1|2−3|=1.
题意:给你两个由二进制数表示的字符串a,b,要使a=b,并且花费最少,a可以进行如下两个操作,1:交换a字符串的两个的数,花费为|i-j| 2:改变第i个数,1变0,0变1,花费为1
分析:如果进行交换两个数的操作,那么当|i-j|>2的时候就不划算了。当|i-j|=1时,并且a[i]!=a[j],如果交换的话,花费为1,如果改变值得话,花费为2。其余情况均是改变值的时候最划算。所以当|i-j|=1,并且a[i]!=a[j]时,让a[j]=b[j]。其余每步都进行改变值花费为1的操作,即ans++。
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 int main() 6 { 7 int n; 8 char a[1000006],b[1000005]; 9 while(~scanf("%d",&n)) 10 { 11 scanf("%s",a+1); 12 scanf("%s",b+1); 13 int ans=0; 14 for(int i=1;i<=n;i++) 15 { 16 if(a[i]!=b[i]) 17 { 18 if(a[i+1]!=b[i+1]&&a[i+1]!=a[i]) 19 a[i+1]=b[i+1]; 20 ans++; 21 } 22 } 23 printf("%d ",ans); 24 } 25 return 0; 26 }