【codeforces】【01字符串匹配】Equalize【Manthan, Codefest 18 (rated, Div. 1 + Div. 2)】

Description:

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.

Input:

           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:

           Output the minimum cost to make the string aa equal to bb.

Examples:

input

3
100
001

output

2

input

4
0101
0011

output

1

 

题意:

           给定两个01串,要求将串a变成串b,两种操作。

1.交换a中两个位置的字符,花费为 abs( i - j )。

2.将任意字符翻转,花费为 1。

思路:

      本题就是一个简单贪心做法,如果 i 位置失配,就看 i+1 位置是否也失配,如果失配,就将 i 位置和 i+1 位置交换,否则就将 i 位置翻转。

      十分简单的一个贪心做法,在写这题的时候却在考虑各种后方有无可交换字符的情况,着实太蠢......

代码:

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#define rep(i,a,b) for(int i = a;i <= b;i++)
using namespace std;
const int N = 1e6+100;

char a[N],b[N];

void change(int pos)
{
	if(a[pos] == '0') a[pos] = '1';
	else a[pos] = '0';
}

int main()
{
	int len;
	scanf("%d",&len);
	scanf("%s",a+1);
	scanf("%s",b+1);
	int ans = 0;
	rep(i,0,len)
	{
		if(a[i]!=b[i])
		{
			if(i == len) ans++;
			else if(a[i] != a[i+1] && a[i+1] != b[i+1])
			{
				ans++;
				change(i);
				change(i+1);
			}
			else ans++;
		}
	}
	printf("%d\n",ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41552508/article/details/82344158
今日推荐