CodeForces 1322A - Unusual Competitions【括号匹配+思维】

题意:

  给出一串长为 \(n\) 的由 \('('\;\)\(\;')'\) 组成的括号序列。可以进行操作:选取一段子串,把该子串的顺序重新调整,使得每个括号都能匹配。一次操作的数量为子串的长度,求出使得整个串都能匹配的最少操作数,或判断不能达到要求。
数据范围:\(1\leq n \leq 10^6\)

分析:

  栈,碰到右括号进栈,左括号出栈,如果最后栈不为空,输出 \(-1\) ,否则输出 \(ans*2\)

代码:

#include <bits/stdc++.h>
using namespace std;
const int N=1e6+6;
char ss[N];
int main()
{
    int n,ans=0,t=0;
    scanf("%d",&n);
    scanf("%s",ss+1);
    for(int i=1;i<=n;i++)
    {
        if(ss[i]==')')
            t++;
        else
        {
            t--;
            if(t>=0)
                ans++;
        }
    }
    if(t)
        printf("-1\n");
    else
        printf("%d\n",2*ans);
    return 0;
}

posted @ 2020-03-10 21:59  xzx9  阅读(206)  评论(0编辑  收藏  举报