【思维】【CF】1615C - Menorah

103 阅读2分钟
  • 博客主页: blog.csdn.net/qq_50285142
  • 👍欢迎点赞👍⭐️收藏⭐️❤️关注❤️留言 📝 如有错误,敬请指正
  • 🎈一看一温习,一码一收获🎈

题目链接:
codeforces.com/problemset/…

将字符串a转化为字符串b,选择a中1保持,其余全部反转,为一次操作。求转化为b的最小操作次数。


我们要把从a串状态变成b串:
计算不相等的位置中 a串1与0的数量是否相等,相等的话我们可以用交换操作达成目的此时答案是
交换次数 * 2

如果a串与b串中有同一位置等于1
我们就可以优先操作该位置,操作后该位置不变,之前与b串不相等的地方会相等,相等的地方会不等。
所以我们也可以计算原a串中相同位置的0与1的数量是否相等,相同1的数量要减1(减去用来翻转的第一次),如果相同,我们同样可以通过交换操作达成目标,此时答案是交换次数 * 2 + 我们第一次的1次翻转


#include<bits/stdc++.h>
using namespace std;
const int N = 1e3+5,M = 1e6+5;

void solve()
{
	int n;
	cin>>n;
	string a,b;
	cin>>a>>b;
	int s1=0,s2=0,d1=0,d2=0;
	int res = 1e9;	
	if(a == b)
	{
		cout<<0<<endl;
		return;
	 } 
	for(int i=0;i<n;i++)
	{
		if(a[i] != b[i])
		{
			if(a[i] == '1') d1++;
			else d2++;
		}
		else if(a[i]==b[i])
		{
			if(a[i]=='1') s1++;
			else s2++;
		}
	}
	if(d1 == d2) res = min(res,d1 + d2);
	
	if(s1)
	{
		s1 -- ;
		if(s1 == s2) res = min(res,s1 + s2 + 1);
	}
	cout<<(res != 1e9 ? res : -1)<<endl;
}

int main()
{
	int t;
	cin>>t;
	while(t--) solve();
	return 0;
 } 

往期优质文章推荐