C. Equalize(思维)

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

题意:两个长度为n只含有0和1的字符串a,b,求最少花费多少可以将a字符串变成b字符串

有两种操作:

1.将当前位置的字符取反(即0变成1,1变成0),花费1

2.将位置i和位置j的字符交换,花费为abs(i-j).

思路:

我们可以发现,位置i不相同,且位置j也不相同(j>i),如果交换后都可以对应位置与b相同,那么这两个位置有两种选择

自身取反,花费2,交换位置花费j-i;所以当i,j相邻时,选择交换方式较优,不相邻时选择自身取反的方式较优

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 1e6+5;
char a[N],b[N];
int main(){
	int n;
	scanf("%d%s%s",&n,a,b);
	a[n]=b[n]='1';
	int ans=0;
	for(int i=0;i<n;i++){
		if(a[i]!=b[i]){
			if(a[i+1]!=b[i+1]&&a[i]==b[i+1]){
				ans++;
				i++;
			}
			else ans++;
		}
	}
	printf("%d\n",ans);
return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值