Codeforces Round #138 (Div. 1) --- A. Bracket Sequence

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_37868325/article/details/97180992

题意:给定一个括号[]()的组成字符串,求其合法的括号子序列,包含合法[]对数最多的一个。

思路,很简单因为合法的+合法的=合法的,合法的可以嵌套在合法的内部。所以,匹配方式唯一,就一个stack匹配一下括号之见的合法关系,然后求求[]的个数,记录[]最多的一个即可

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mod  200005
#define maxn 100005
int m,num,ans,ansl,numm,len;
char ch[maxn];
stack<int>s;
struct AA
{
    int l,r,x;
    bool operator<(const AA&aa)const
    {
        return l<aa.l;
    }
}pos[maxn];
int main()
{
    while(!s.empty()) s.pop();
    scanf("%s",ch);
    m=strlen(ch);int c;
    for(int i=0;i<m;i++)
    {
        if(ch[i]=='['||ch[i]=='(') s.push(i);
        else
        {
            if(s.size()>0)
            c=s.top();
            else {c=-1;}
            if(c!=-1&&((ch[i]==']'&&ch[c]=='[')||(ch[i]==')'&&ch[c]=='(')))
               {
                   s.pop();
                   pos[++num].l=c;
                   pos[num].r=i;
                   if(ch[i]==']')
                   pos[num].x=1;
                   else pos[num].x=0;
               }
               else s.push(i);
        }
        //if(s.size()>m) while(1){}
    }
    int x=-9,y=-10;
    sort(pos+1,pos+1+num);
    for(int i=1;i<=num;i++)
    {
        if(pos[i].l>y+1){x=pos[i].l,y=pos[i].r;numm=pos[i].x;}
        else
        {
            y=max(y,pos[i].r);
            numm+=pos[i].x;
        }
        if(ans<numm)
        {
            ans=numm;
            len=y-x+1;
            ansl=x;
        }
    }
    printf("%d\n",ans);
    for(int i=0;i<len;i++)
    {
        printf("%c",ch[i+ansl]);
    }
    puts("");
}

猜你喜欢

转载自blog.csdn.net/qq_37868325/article/details/97180992