CF1503 A. Balance the Bits 暴力贪心

题解:符合要求的01串需满足首尾为1且0,1的个数都为偶数。括号序列的构造:前k/2个1为左括号,后k/2个1为右括号,0位置上左右括号轮换。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
char a[200005],b[200005];
bool check(char *c)
{
    stack<int> s;
    int i=0;
    while(c[i])
    {
        if(c[i]=='(')s.push(1);
        else
        {
            if(s.empty())return 0;
            s.pop();
        }
        i++;
    }
    if(s.size())return 0;
    return 1;
}
void solve(){
    int n;
    cin>>n;
    fill(a,a+n+1,0);
    fill(b,b+n+1,0);
    string t;
    cin>>t;
    int cnt=0;
    for(int i=0;i<n;i++)
    {
        if(t[i]=='1')cnt++;
    }
    if( cnt%2==1 || n%2==1)
    {
        cout<<"NO"<<endl;
        return ;
    }
    int i=0,j=n-1;
    while(i<j)
    {
        while(t[i]=='0')i++;
        while(t[j]=='0')j--;
        if(i>j)break;
        a[i]=b[i]='(';
        b[j]=a[j]=')';
        i++;
        j--;
    }
    int op=0;
    for(int k=0;k<n;k++)
    {
        if(a[k]==0)
        {
            if(op){
                a[k]='(';
                b[k]=')';
            }
            else {
                a[k]=')';
                b[k]='(';
            }
            op^=1;
        }
    }
    if(check(a) && check(b))
    {
        cout<<"YES"<<endl;
        cout<<a<<endl<<b<<endl;
    }
    else cout<<"NO"<<endl;
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int T;
    cin>>T;
    while(T--)solve();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值