codeforces-223A-Bracket Sequence

来源:互联网 发布:mysql group concat 编辑:程序博客网 时间:2024/05/28 22:08

从前往后进行括号匹配。

如果匹配到,就把当前位置,和被匹配的括号的位置标记为对应括号的位置。

然后一段连续的不带0的区域即时一个可用的子串。

然后从这些字串中寻找中括号最多的字串。

#include <stdio.h>#include<string.h>#include<iostream>#include<algorithm>#include<stdlib.h>#include<math.h>#include<stack>#define LL long longusing namespace std;int a[200000];int num[200000];int b[200000];int vis[200000];stack<int>sta;stack<int>stb;char str[200001];int main(){    int i,n,k;    while(~scanf("%s",str))    {        memset(num,0,sizeof(num));        memset(b,0,sizeof(b));        int len=strlen(str);        for(i=0; i<len; i++)        {            if(str[i]=='(')a[i+1]=1;            if(str[i]=='[')            {                a[i+1]=2;                num[i+1]++;            }            if(str[i]==')')a[i+1]=3;            if(str[i]==']')a[i+1]=4;            num[i+1]+=num[i];        }        while(!sta.empty())sta.pop();        while(!stb.empty())stb.pop();        for(i=1; i<=len; i++)        {            if(a[i]<=2)            {                sta.push(a[i]);                stb.push(i);            }            else            {                if(sta.empty())                {                    continue;                }                int xx,yy;                xx=sta.top();                sta.pop();                yy=stb.top();                stb.pop();                if(xx%2==a[i]%2)                {                    b[i]=yy;                    b[yy]=i;                }                else                {                    while(!sta.empty())sta.pop();                    while(!stb.empty())stb.pop();                }            }        }       /* for(i=1;i<=len;i++)        {            cout<<b[i]<<" ";        }        cout<<endl;*/        int maxx=0;        int ma=0;        int st=-1;        int ed=-1;        int ss=1;        for(i=1;i<=len+1;i++)        {            if(b[i]==0)            {                if(maxx<ma)                {                    maxx=ma;                    ed=i-1;                    st=ss;                }                ss=i+1;                ma=0;            }            else            {                if(a[i]==2)ma++;            }        }        cout<<maxx<<endl;        if(maxx>0)        {            for(i=st;i<=ed;i++)            {                printf("%c",str[i-1]);            }            cout<<endl;        }    }    return 0;}


0 0
原创粉丝点击