codeforces 5C Longest Regular Bracket Sequence(dp+技巧)【最长连续括号模板】

This is yet another problem dealing with regular bracket sequences.

We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.

You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.

Input

The first line of the input file contains a non-empty string, consisting of «(» and «)» characters. Its length does not exceed 106.

Output

Print the length of the longest substring that is a regular bracket sequence, and the number of such substrings. If there are no such substrings, write the only line containing "0 1".

Examples
input
)((())))(()())
output
6 2
input
))(
output
0 1

 【题解】 先说一下,这本来是个区间dp,,但是那个推公式很麻烦,所以就用了这个方法,不过原理是差不多的,

 分析: 

 题目要求一个乱序括号序列的最长连续合法序列,及此长度的合法序列个数,那么我们可以扫两次。

先从左往右扫,遇见(就num++,遇见)并且num>0,就把此)标记为1,并且num--,意味着有一对已经匹配了,剩下num--个(了。

然后同样从右往左扫,操作相同;

扫完后再次从左往右扫一遍,统计连续标记的最大值,并记录其个数即可。


【AC代码】

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=1e6+10;
int maxn,m,n,len;
char s[N];
int vis[N];

int main()
{
    while(~scanf("%s",s))
    {
        memset(vis,0,sizeof(vis));
        maxn=-1;
        len=strlen(s);
        int cnt=0;
        for(int i=0;i<len;++i)
        {
            if(s[i]=='(')
                cnt++;
            else if(s[i]==')')
            {
                if(cnt)
                   vis[i]=1;
                cnt--;
            }
            if(cnt<0) cnt=0;
        }
        cnt=0;
        for(int i=len-1;i>=0;--i)
        {
            if(s[i]==')')
                cnt++;
            else if(s[i]=='(')
            {
                if(cnt)
                   vis[i]=1;
                cnt--;//注意--
            }
            if(cnt<0) cnt=0;//这里注意,,WA了好几发呢
        }
        cnt=0;
        n=0;
        for(int i=0;i<len;++i)
        {
            if(vis[i])
            {
                cnt++;
            }
            else
            {
                cnt=0;
            }
            if(cnt>maxn)
            {
                maxn=cnt;
                n=1;
            }
            else if(cnt == maxn)
                n++;
        }
        if(maxn==0) n=1;//特判  注意别忘了
        printf("%d %d\n",maxn,n);
    }
    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值