Balance the Bits

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 ss of length nn. Construct two balanced bracket sequences aa and bb of length nn such that for all 1≤i≤n1≤i≤n:

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

If it is impossible, you should report about it.

Input

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

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

The next line contains a string ss of length nn, consisting of characters 0 and 1.

The sum of nn across all test cases does not exceed 2⋅1052⋅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 aa and bb satisfying the conditions on the next two lines.

If there are multiple solutions, you may print any.

Input:

3
6
101101
10
1001101101
4
1100

Out:

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

题意:给一个偶数的二进制数字,让我们构造两个长度为n的平衡括号(如“()(())”就是平衡括号)。若s[i] == ‘0’,两个字符串对应位置的括号要相反。== ‘1’则相同。

题解:我们需要偶数个0来构造平衡括号,0时偶数的话,保证n时偶数,那么1的数量一定也会是偶数不然则不能构造。其次就是第一个和最后一个一定分别是“(”,")" ,因此s[0] == '1',s[n-1] -== '1'。不然也不能构造。

其余就是遇到1先添加“(”左括号,再次构造时就是“)”右括号,以此轮回。

遇到0,给两个待构造平衡括号分别添加两个相反的括号即可。

代码:

#include <bits/stdc++.h>
#define int long long 
using namespace std;

const int N = 2e5 + 10;

void solve(){
	int n; cin >> n;
	string s; cin >> s;
	int c0 = 0;
	for(int i = 0;i < n;i++) if(s[i] == '0') c0++;
	if(s[0] != '1' || s[n-1] != '1' || (c0 & 1)){
		cout <<"NO\n";
		return;
	}
	string ans1="(",ans2 = "(";
	
	int cnt1 = 0,cnt2 = 0;
	for(int i = 1;i <n - 1;i++){
		if(s[i] == '1'){
			if((cnt1&1) == 0){
				ans1 += "(";
				ans2 += "(";
			}else{
				ans1 += ")";
				ans2 += ")";
			}
			cnt1++;
		}else{
			if(cnt2&1){
				ans1 += "(";
				ans2 += ")";
			}else{
				ans2 += "(";
				ans1 += ")";
			}
			cnt2++;
		}
	}
	ans1+=")";ans2+=")";
	
	cout <<"YES\n" << ans1 <<endl <<ans2 <<endl;
}

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值