codeforces 1503 A. Balance the Bits(1300)

链接:https://codeforces.com/problemset/problem/1503/A

题意:

给你一个长度为n的01字符串,要求你构造两个合理的括号序列,且满足

  • if si=1si=1, then ai=biai=bi
  • if si=0si=0, then ai≠bi

题解:

已知合理括号序列一定有 ‘(’和‘)’的数量相同且任意时候‘(’的数量一定比‘)’多;那我们很容易想到能否构造的条件:0和1的数量相同且首尾均为1;

接下来看怎么构造,先考虑1的位置;在1的位置a,b串的符号都是相同的,那我们只需要前面一半1为‘(’,后面一半1为‘)’;再考虑0,只需要对a处理,当‘(’的数量大于‘)’时,填‘)’;反之,填‘(’;b的对应位置反着来就好;

代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n;
		cin >> n;
		string s;
		string a, b;
		cin >> s;
		a = s;
		b = s;
		int cnt = 0;
		for (int i = 0; i < n; i++)
		{
			if (s[i] == '1')
				cnt++;
		}
		if (cnt % 2 || (n - cnt) % 2 || s[0] == '0' || s[n - 1] == '0') 
		{
			cout << "NO" << endl;
		}
		else
		{
			cout << "YES" << endl;
			int cnt1 = 0;
			int flag = 0;
			for (int i = 0; i < n; i++)
			{
				if (s[i] == '1' && flag == 0)
				{
					a[i] = b[i] = '(';
					cnt1++;
				}
				else if (s[i] == '1' && flag == 1)
				{
					a[i] = b[i] = ')';
				}
				if (cnt1 == cnt / 2)
				{
					flag = 1;
				}
			}
			int c1 = 0, c2 = 0;
			for (int i = 0; i < n; i++)
			{
				if (s[i] == '0')
				{
					if (c1 > c2)
					{
						a[i] = ')';
						b[i] = '(';
						c1--;
						c2++;
					}
					else
					{
						a[i] = '(';
						b[i] = ')';
						c1++;
						c2--;
					}
				}
			}
			cout << a;
			cout << endl;
			cout << b;
			cout << endl;

		}
		
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值