返回顶部

Codeforces Round #712 (Div. 2) C. Balance the Bits (构造)

  • 题意:给你一个长度为\(n\)的01串\(s\),要求你构造出两个长度为\(n\)的合法括号序列\(a\)\(b\),如果\(s_i=1\),那么\(a_i=b_i\),如果\(s_i=0\),那么\(a_i \ne b_i\),问你能否构造出两个序列,若可以,输出他们.

  • 题解:首先,\(s_1=s_n=1\),这是一定要成立的,其次,因为合法的括号序列左括号和右括号的数量一定相等 ,所以\(s\)\(0\)的个数一定要是偶数,接下来考虑构造的情况,第一个位置一定是(,最后一个位置一定是),那么我们可以让第一个\(s_i=0\)的位置给),这个)可以和\(s_1=1\)来匹配,最后一个\(s_i=0\)的位置给(,和\(s_n=1\)来匹配,那么对于\(0\)的位置我们可以这样给:\()()()(....()(\),这样反转过来就变成了\(()()...()\),一定是合法的,对于\(1\)的位置,我们让前一半的\(1\)为(,后一半为)即可.

  • 代码:

    #include <bits/stdc++.h>
    #define ll long long
    #define fi first
    #define se second
    #define pb push_back
    #define me memset
    #define rep(a,b,c) for(int a=b;a<=c;++a)
    #define per(a,b,c) for(int a=b;a>=c;--a)
    const int N = 1e6 + 10;
    const int mod = 1e9 + 7;
    const int INF = 0x3f3f3f3f;
    using namespace std;
    typedef pair<int,int> PII;
    typedef pair<ll,ll> PLL;
    ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
    ll lcm(ll a,ll b) {return a/gcd(a,b)*b;}
     
     
     
    int main(){
        ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
        int _;
        cin>>_;
        while(_--){
            int n;
            string s;
            cin>>n;
            cin>>s;
    
            int cnt0=0,cnt1=0;
            for(auto w:s){
                if(w=='0') cnt0++;
                else cnt1++;
            }
    
            if(cnt0&1 || s[0]=='0' || s[n-1]=='0'){
                cout<<"NO\n";
                continue;
            }
    
            string ans;
            int cnt=0,flag=0;
            rep(i,0,n-1){
                if(s[i]=='1'){
                    cnt++;
                    if(cnt<=cnt1/2) ans.pb('(');
                    else ans.pb(')');
                }
                else{
                    if(!flag){
                        ans.pb(')');
                    }
                    else{
                        ans.pb('(');
                    }
                    flag=1-flag;
                }
            }
    
            string ans_;
            rep(i,0,n-1){
                if(s[i]=='1') ans_.pb(ans[i]);
                else{
                    if(ans[i]=='(') ans_.pb(')');
                    else ans_.pb('(');
                }
            }
    
            cout<<"YES\n";
            cout<<ans<<'\n'<<ans_<<'\n';
        }
     
     
     
        return 0;
    }
    
posted @ 2021-04-16 09:35  _Kolibri  阅读(94)  评论(0)    收藏  举报