Codeforces Round #712 (Div. 2). Balance the Bits

C. Balance the Bits

time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters ‘+’ and ‘1’. For example, sequences ‘(())()’, ‘()’, and ‘(()(()))’ are balanced, while ‘)(’, ‘(()’, and ‘(()))(’ are not.

You are given a binary string s of length n. Construct two balanced bracket sequences a and b of length n such that for all 1≤i≤n:

if si=1, then ai=bi
if si=0, then ai≠bi
If it is impossible, you should report about it.

Input
The first line contains a single integer t (1≤t≤104) — the number of test cases.

The first line of each test case contains a single integer n (2≤n≤2⋅105, n is even).

The next line contains a string s of length n, consisting of characters 0 and 1.

The sum of n across all test cases does not exceed 2⋅105.

Output
If such two balanced bracked sequences exist, output “YES” on the first line, otherwise output “NO”. You can print each letter in any case (upper or lower).

If the answer is “YES”, output the balanced bracket sequences a and b satisfying the conditions on the next two lines.

If there are multiple solutions, you may print any.

Example
inputCopy

3
6
101101
10
1001101101
4
1100

outputCopy

YES
()()()
((()))
YES
()()((()))
(())()()()
NO

Note
In the first test case, a="()()()" and b="((()))". The characters are equal in positions 1, 3, 4, and 6, which are the exact same positions where si=1.

In the second test case, a="()()((()))" and b="(())()()()". The characters are equal in positions 1, 4, 5, 7, 8, 10, which are the exact same positions where si=1.

In the third test case, there is no solution.

解题思路

关键点:贪心,构建算法
关键描述
if si=1, then ai=bi
if si=0, then ai≠bi
1.特殊情况,由于最后形成的括号必须形成前后互相匹配,所以是 s[0] 和 s[1]必须是1,字符串的长度必须是偶数,注意统计的字符 0 的个数也必须是偶数,因为反过来的括号和有个反过来的括号和它匹配
2. 统计字符 0 的个数,根据字符 1 的个数进行左右平分,左边的为‘(’,右边的为‘)’,此时给两个字符串分配相同的字符
3. 字符 0 分配不同的字符,轮流先后加入括号符
在这里插入图片描述

参考代码

#include<iostream>
#include<string>
using namespace std;

int main()
{
	int t,n,num;
	string s;
	cin>>t;
	
	while(t--){
		cin>>n>>s;
		num=0;
		string ab[2];
		for(int i=0;i<n;i++)
			num+=s[i]=='0';
		if(s[0]=='0' || s[n-1]=='0' || num%2){
			puts("NO");
			continue;
		}
		int j=0;
		int tmp=0;
		for(int i=0;i<n;i++){
			if(s[i]=='1'){
				if(n-num>2*j){
					ab[0]+='('; ab[1]+='(';
				}else{
					ab[0]+=')'; ab[1]+=')';
				}
				j++;
			}else{
				ab[tmp]+='(';
				ab[!tmp]+=')';
				tmp=!tmp;	
			}	
		}
		puts("YES");
		cout<<ab[0].c_str()<<endl;
		cout<<ab[1].c_str()<<endl;
	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值