Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define ll long long
- #define _test int _TEST; cin>>_TEST; while(_TEST--)
- #define ff first
- #define ss second
- #define pb push_back
- int main()
- {
- _test
- {
- int n;
- string s;
- cin>>n>>s;
- vector<int> v;
- for(int i=0; i<n;)
- {
- int j = i+1;
- while(j<n && s[i]==s[j])
- j++;
- v.pb(j-i);
- i = j;
- }
- int tot = accumulate(v.begin(), v.end(), 0);
- if(n%2 || tot%2)
- {
- cout<<"NO\n";
- continue;
- }
- vector<vector<int>> dp(n+10, vector<int> (n+10, -1));
- dp[v.size()][0] = 1;
- function<int(int, int)> check = [&](int ind, int value)
- {
- if(ind == v.size())
- return (int)(value == 0);
- if(dp[ind][value] != -1) return dp[ind][value];
- int x = 0;
- int y = 0;
- x = check(ind+1, value+v[ind]);
- if(value-v[ind] >= 0) y = check(ind+1, value-v[ind]);
- return dp[ind][value] = (x|y);
- };
- if(check(1, v[0]))
- {
- cout<<"YES\n";
- n = v.size();
- string ans = "";
- for(int i=0; i<v[0]; i++) ans += '(';
- int value = v[0];
- for(int i=1; i<n; i++)
- {
- if(dp[i+1][value+v[i]] == 1)
- {
- for(int j=0; j<v[i]; j++) ans += '(';
- value += v[i];
- }
- else
- {
- for(int j=0; j<v[i]; j++) ans += ')';
- value -= v[i];
- }
- }
- cout<<ans<<"\n";
- }
- else
- cout<<"NO\n";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment