Codeforces Contest 1095 problem E Almost Regular Bracket Sequence ——括号匹配

You are given a bracket sequence s consisting of n opening ‘(’ and closing ‘)’ brackets.

A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters ‘1’ and ‘+’ between the original characters of the sequence. For example, bracket sequences “()()”, “(())” are regular (the resulting expressions are: “(1)+(1)”, “((1+1)+1)”), and “)(” and “(” are not.

You can change the type of some bracket si. It means that if si= ‘)’ then you can change it to ‘(’ and vice versa.

Your task is to calculate the number of positions i such that if you change the type of the i-th bracket, then the resulting bracket sequence becomes regular.

Input
The first line of the input contains one integer n (1≤n≤106) — the length of the bracket sequence.

The second line of the input contains the string s consisting of n opening ‘(’ and closing ‘)’ brackets.

Output
Print one integer — the number of positions i such that if you change the type of the i-th bracket, then the resulting bracket sequence becomes regular.

Examples
inputCopy
6
(((())
outputCopy
3
inputCopy
6
()()()
outputCopy
0
inputCopy
1
)
outputCopy
0
inputCopy
8
)))(((((
outputCopy
0

题意:

给你一串字符串,( 和 )在左右就是匹配,)(就不是匹配,让你改变任意一个地方的括号,(改成),)改成(,使得这个字符串是匹配的字符串,问你有多少种方法。

题解:

想法挺简单的,只要想出所有情况即可了,最后你就会发现这样一件事情:完美匹配和剩下的字符不是两个或者不是相同的就不可以,然后只需要判断剩下两个字符的情况,最后发现如果是’(’,那么从第二个多余的’(’开始接下来都是可以改变的,相反的话是第一个多余的’)‘开始都是可以改变的,举个例子:
((()))))是前面4个’)'可以改变,((()))((,只有最后一个可以被改变,因为前面的是完美匹配了,))(())只有第一个可以改变,其他是完美匹配了。

#include<bits/stdc++.h>
using namespace std;
#define pa pair<char,int>
const int N=1e6+5;
char s[N];
pa st[N];
int judge(char a,char b)
{
    if(a=='('&&b==')')
        return 1;
    return 0;
}
int main()
{
    int n,top=0;
    scanf("%d",&n);
    scanf("%s",s+1);
    for(int i=1;i<=n;i++)
    {
        if(top==0||judge(st[top].first,s[i])==0)
            st[++top]={s[i],i};
        else
            top--;
    }
    int k=0;
    if(top==2&&st[1].first==st[2].first)
        return 0*printf("%d\n",st[1].first=='('?(n-st[2].second)/2+1:(st[1].second-1)/2+1);
    printf("0\n");
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值