当前位置: 代码迷 >> 综合 >> C. Balance the Bits
  详细解决方案

C. Balance the Bits

热度:94   发布时间:2023-11-23 07:01:15.0

题:
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≤10^4) — the number of test cases.

The first line of each test case contains a single integer n (2≤n≤2?10^5, 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?10^5.

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

input
3
6
101101
10
1001101101
4
1100

output
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.

题意:
给出一串由’0’和’1’组成的字符串s,要求构造两个只由左右括号组成的字符串a和b,如果s[i] = ‘0’,则a[i]!=b[i],如果s[i] = ‘1’,则a[i] = b[i]。
若最后构造的字符串a和b的左右括号都是平衡配对的,则输出YES和两个字符串,反之则输出NO。

思路:
如果字符串a和b要平衡配对,那么第一个元素和最后一个元素必定都是左括号和右括号,也就是说,这两个位置的元素一定是相同的,则相同位置的字符串s的元素也必须为’1’。
字符串s中’1’和’0’的个数必须都是偶数,如果是奇数的话,则无论怎么构造也无法满足平衡配对。
然后将a和b的元素在s左半边’1’的相同位置用左括号代替,右半边’1’用右括号代替,如果s[i] = ‘0’,奇数次操作a和b分别用左括号和右括号代替,偶数次操作a和b分别用右括号和左括号代替,如此反复,奇数次操作和偶数次操作交换也可成立。

#include<iostream>
#include<cstring>
#include<string>
#include<stack>
using namespace std;typedef long long ll;
const int N = 2e5 + 5;int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);int T;cin >> T;while(T--){
    ll n, i, a0 = 0, a1 = 0;string a, b0, b1;b0 = "";b1 = "";cin >> n;stack<char> p1, p2;cin >> a;for(i = 0; i < n; ++i){
    if(a[i] == '0')a0++;elsea1++;}if(a0 % 2 || a1 % 2){
    cout << "NO" << endl;continue;}if(a[0] != a[n-1] || a[0] != '1'){
    cout << "NO" << endl;continue;}ll k1 = 0;bool z = 0;for(i = 0; i < n; ++i){
    if(a[i] == '1'){
    if(k1 < a1 / 2){
    b0 += '(';b1 += '(';k1++;}else{
    b0 += ')';b1 += ')';}}else{
    if(!z){
    b0 += '(';b1 += ')';z = 1;}else{
    b0 += ')';b1 += '(';z = 0;}}}cout << "YES" << endl;for(i = 0; i < n; ++i)cout << b0[i];cout << endl;for(i = 0; i < n; ++i)cout << b1[i];cout << endl;}return 0;} 
  相关解决方案