5C-codeforce Longest Regular Bracket Sequence

C. Longest Regular Bracket Sequence
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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 exceed106.

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,挺水的,题意是让求最长合法括号序列的长度,也就是说在这个长度内括号都是匹配的
#include<stdio.h>
#include<iostream>
#include<string>
#include<algorithm>
#include<string.h>
#include<map> 
#include<math.h>
#include<set>
#include<queue>
#include<vector>
#include<stack>
using namespace std;
int dp[1000001];//dp数组存的是到当前位置(右括号)最长序列的长度 
int main()
{
	string s;
	int i;
	stack<int>s1;
	while(cin>>s)
	{
		memset(dp,0,sizeof(dp));
		while(!s1.empty())
		s1.pop();
		for(i=0;i<s.size();i++)
		{
			if(s[i]=='(')
			{
				s1.push(i);
			}
			else//如果是右括号 
			{
				if(!s1.empty())
				{
				dp[i]=i-s1.top()+1;//计算当前右括号与左括号的距离(长度) 
				if(s1.top()>0)
				{
					dp[i]+=dp[s1.top()-1];//加上前边的长度 
				}
				s1.pop();
			}
			}
		}
		int max=0,n=1;
		for(i=0;i<s.size();i++)
		{
			if(dp[i]>max)
			{
				n=1;
				max=dp[i];
			}
			else if(dp[i]==max)
			n++;
		}
		if(max==0)
		printf("0 1\n");
		else
		printf("%d %d\n",max,n);
	}	
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值