题面(The Problem):
题目大意(The meaning of the problem):
T组数据,给定一个n,下面是n长的字符串,输出两个只包含’(‘和’)'的字符串,保证括号是正确的(例如“()“是正确的,”)(“是不正确的)。输入了1的位置两个字符串相等,输入0的部分两个输出字符串不同。
思路(Method):
首先头和尾必须分别是(和),所以第一个输入和最后一个输入必须都是1。判断1的个数和0的个数是否都为偶数(事实上判断一个就可以因为n保证是偶数),如果不相等肯定输出NO。输出的字符串在1的前一半位置上输出(,后一半输出),中间0的部分就交换着输出’)‘和’(‘,所以没两个0的括号会相互抵消掉。
#include "bits/stdc++.h"
#define endl "\n"
using namespace std;
int main(void) {
int t;
cin >> t;
while (t--) {
string str1, str2;
int n;
string str;
cin >> n >> str;
str1.resize(n );
str2.resize(n );
int cnt1 = 0, cnt2 = 0;
if (str[0] == '0' || str[n - 1] == '0') {//头和尾必须分别是(),所以必须为1
cout << "NO" << endl;
continue;
}
for (auto ch : str) {
if (ch == '0') cnt1++;
else cnt2++;
}
if (cnt1 % 2 == 1) {//如果有任意一个是奇数,就会导致最后两字符串不平衡,就没有结果。
cout << "NO" << endl;
continue;
}
bool flag = false;
cnt2 /= 2;
for (int i = 0; i < n; ++i) {
if (str[i] == '1') {
if (cnt2) {
str1[i] = str2[i] = '(';
cnt2--;
}else {
str1[i] = str2[i] = ')';
}
}else {
if (!flag) {
str1[i] = '(';
str2[i] = ')';
}else {
str1[i] = ')';
str2[i] = '(';
}
flag ^= 1;
}
}
cout << "YES" << endl << str2 << endl << str1 << endl;
}
return 0;
}