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;
}