Longest Regular Bracket Sequence -括号处理

C - Longest Regular Bracket Sequence
Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u

Description

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

Sample Input

Input
)((())))(()())
Output
6 2
Input
))(
Output
0 1

 

这个题不会做

想不到科学的方法,导致分支太多,太复杂

听了一大神的思路:

先从左for到右 遇到( cun++    遇到)并且此时cun>0 即该右括号是合法的 vis[右括号]=1

同理 再从右到左 标记所有 合法的左括号

最后把vis数组for一遍 if (vis[i]) cun++;  遇到vis[]==0 就判断是否比max大,  从而最后筛选到最大值和个数


#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <queue>
#include <algorithm>
#include <iostream>
using namespace std;
char tm[1000000+5];
int vis1[1000000+5]; 
int ans[500000+5];

int main()
{
	
	scanf("%s",tm+1);
	int len=strlen(tm+1);
int i,	cun=0;
	for (i=1;i<=len;i++)
	{
		if (tm[i]=='(')
			cun++;
		
		if (tm[i]==')')
		{
			if (cun)
			{
				vis1[i]=1;
			}
			cun--;
		} 
		if (cun<0) 
			cun=0;
	}
	cun=0;
	for (i=len;i>=1;i--)
	{
		if (tm[i]==')')
			cun++;
		
		if (tm[i]=='(')
		{
			if (cun)
			{
				vis1[i]=1;
			}
			cun--;
		} 
		if (cun<0)
			cun=0;
	}
	
	int ok=0;
	cun=0;
	int max=0;
	for (i=1;i<=len;i++)
	{
		
		if (vis1[i]==1)
			cun++;
		else
		cun=0;

		if (cun>max) max=cun,ok=1;
		else if (cun==max)
			ok++;
		
		}
	if (max==0) ok=1;
		printf("%d %d\n",max,ok);
 
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值