正文
增加 66 行删除 73 行
61 行未改动626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414561 行未改动## 代码实现```cpp#include <bits/stdc++.h>using namespace std;int main() {ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);int t;cin >> t;while (t--) {int n;string s;cin >> n >> s;// 首尾为0,直接无解if (s[0] == '0' || s[n - 1] == '0') {cout << "NO\n";continue;}// 统计0的数量int cnt0 = 0;for (char c : s) {if (c == '0') cnt0++;}// 0的数量为奇数,无解if (cnt0 % 2 != 0) {cout << "NO\n";continue;}cout << "YES\n";string a, b;int pos = 0; // a序列的括号平衡值bool separate = 0; // 0的奇偶状态标记for (int i = 0; i < n; i++) {// 最后一位强制为右括号,保证序列闭合if (i == n - 1) {a += ')';b += ')';break;}if (s[i] == '1') {// 平衡足够时放右括号,否则放左括号if ((separate && pos >= 1) || pos >= 2) {pos--;a += ')';b += ')';} else {pos++;a += '(';b += '(';}} else {if (!separate) {// 奇数个0:a放右括号(数值-1),b放左括号(数值+1)pos--;a += ')';b += '(';} else {// 偶数个0:a放左括号(数值+1),b放右括号(数值-1)pos++;a += '(';b += ')';}separate ^= 1; // 翻转状态}}cout << a << '\n' << b << '\n';}return 0;}```## 复杂度分析- **时间复杂度**:每组数据 $(O(n))$,总复杂度 $O(\sum n)$,符合 $2\times10^5$ 的数据范围要求。- **空间复杂度**:$(O(n))$ 用于存储答案字符串,额外空间为常数级。该构造方法通过数值模型的前缀和约束指导分配策略,严格保证两个序列的前缀平衡始终非负、最终平衡值为 0,完全满足合法括号序列的定义,且严格符合 $s$ 的约束条件。61 行未改动626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713861 行未改动## 代码实现```cpp#include <bits/stdc++.h>using namespace std;long long t;long long n;string s;//长度为n的原始序列string ansa,ansb;long long zcnt;//0的数量int main(){ios::sync_with_stdio(false);cin.tie(0),cout.tie(0);cin >> t;while (t--){bool separate=0;ansa="";ansb="";zcnt=0;cin >> n >> s;if (s[0]=='0' || s[n-1]=='0'){cout << "No" <<'\n';continue;}for (int i=0;i<n;i++){if (s[i]=='0'){zcnt++;}}if (zcnt%2==1){cout << "No" << '\n';continue;}cout << "Yes" << '\n';long long pos=0;//a括号序列左括号没有闭合的值for (int i=0;i<n;i++){if (i==n-1){ansa+=')';ansb+=')';break;}if (s[i]=='1'){if ((separate==1 && pos>=1) || pos>=2){pos--;ansa+=')';ansb+=')';}else{pos++;ansa+='(';ansb+='(';}}else{if (separate==0){pos--;ansa+=')';ansb+='(';separate^=1;}else{pos++;ansa+='(';ansb+=')';separate^=1;}}}cout << ansa << '\n';cout << ansb << '\n';}return 0;}```## 复杂度分析- **时间复杂度**:每组数据 $O(n)$,总复杂度 $O(\sum n)$,符合 $2\times10^5$ 的数据范围要求。- **空间复杂度**:$O(n)$ 用于存储答案字符串,额外空间为常数级。