括号序列的最长合法子段 51Nod - 1478

https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1478

一个合法序列两端肯定是一对匹配的括号 如(...) 单调栈扫一遍 处理出所有配对位置 因为只关心最长 跳着往后找就行

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;

stack <int> stk;
int ptr[maxn];
int n;
char ch[maxn];

void init()
{
    int i,j;
    for(i=0;i<n;i++)
    {
        if(ch[i]=='(') stk.push(i);
        else if(!stk.empty())
        {
            ptr[stk.top()+1]=i+1;
            stk.pop();
        }
    }
}

void solve(int &len,int &cnt)
{
    int i,tmp;
    len=0,cnt=1,tmp=0;
    i=1;
    while(i<=n)
    {
        if(ptr[i]!=0)
        {
            tmp+=(ptr[i]-i+1);
            i=ptr[i]+1;
        }
        else tmp=0,i++;
        if(len<tmp) len=tmp,cnt=1;
        else if(len==tmp&&len!=0) cnt++;
    }
}

int main()
{
    int i,len,cnt;
    scanf("%s",ch);
    n=strlen(ch);
    init();
    solve(len,cnt);
    printf("%d %d\n",len,cnt);
    return 0;
}

//))(

猜你喜欢

转载自blog.csdn.net/sunyutian1998/article/details/83110678
今日推荐