括号序列求唯一解解法

括号序列求唯一解解法。

cf edu132c

统计左括号和右括号个数,如果数量各占总数一半,则必有唯一解。否则,将前一半可变字符做为左括号,后一半作为右括号,交换中间两个,若仍可以得到解,则结果不唯一。否则有唯一解。

#include<bits/stdc++.h>
#define x first
#define y second
 
using namespace std;
typedef long long LL;
const int N = 200010,mod = 1e9 + 7,INF = 0x3f3f3f3f;
int seq[N],l;
char s[N];
int n,m,t;
 
void solve()
{
    cin>>s;
    n = strlen(s);
    l = 0;
    int cnt[3] = {0};
    for(int i = 0;i < n;i++)
    {
        if(s[i] == '(') cnt[0]++;
        else if(s[i] == ')') cnt[1]++;
        else seq[++l] = i;
    }
    if(cnt[0] == n / 2 || cnt[1] == n / 2) 
    {
        cout<<"YES"<<endl;
        return;
    }
    for(int i = 1;i <= n / 2 - cnt[0];i++) s[seq[i]] = '(';
    for(int i = n / 2 - cnt[0] + 1;i <= l;i++) s[seq[i]] = ')';
    swap(s[seq[n/2 - cnt[0]]],s[seq[n/2 - cnt[0] + 1]]);
    int sum = 0;
    for(int i = 0;i < n;i++)
    {
        sum += s[i] == '('? 1 : -1;
        if(sum < 0) 
        {
            cout<<"YES"<<endl;
            return;
        }
    }
    cout<<"NO"<<endl;
}
 
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
 
    cin>>t;
    while (t--)
    {
        solve();
    }
    return 0;   
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值