codeforces 5C Longest Regular Bracket Sequence -- 贪心

该问题涉及正规括号序列,需要找到输入字符串中最长的正规括号子序列及其数量。正规序列可以通过插入加号和数字1形成正确数学表达式。算法思路是找到每个')'与其最近未匹配的'('进行匹配,并累加长度。若存在相邻的两对括号,第二对的长度加上第一对的长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 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 test(s)
input
)((())))(()())
output
6 2
input
))(
output
0 1

这一题想到思路就很简单。重点是找),离它最近的没有被匹配的(就是应该跟它匹配,可以记录这一对有多长。然后,()(),对于这种情况,就是两队相邻,第二队加上第一队长度就好了。


#include<cstdio>
#include<iostream>
#include<stack>

using namespace std;

#define MAXN 1000000

int len[MAXN]={0};

int main(){
#ifndef ONLINE_JUDGE
  freopen("data","r",stdin);
#endif

  string s;
  stack<int> st;
  int k,maxl=0,n=0;
  cin>>s;

  for(int i=0; i<s.size(); i++){
    if('(' == s[i]){
      st.push(i);
    }else{
      if(!st.empty()){
        k = st.top();
        st.pop();

        len[i] = ( k>0 ? len[k-1] : 0 ) + i+1-k;
        if(len[i]>maxl){
          maxl = len[i];
          n = 1;
        }else if(len[i]==maxl)
          n++;
      }
    }
  }

  if(maxl>0)
    cout<< maxl << " " << n << endl;
  else
    cout<<"0 1"<<endl;

#ifndef ONLINE_JUDGE
  fclose(stdin);
#endif

  return 0;
}

之前一个错误的思路就是从第一字符到后面的字符,分别找最大长度,顺着数(,用)来抵消,这样在类似()(()(()(这种情况下,每次都要走完,复杂度为n平方,时间过不去。而贪心的方法复杂度仅为n。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值