【CodeForces】CF26B Regular Bracket Sequence

题目地址:

https://www.luogu.com.cn/problem/CF26B

题面翻译:
给出一个括号的序列,求最长的合法的子序列并输出。
原序列的长度 ≤ 1 0 6 \le 10^6 106

题目描述:
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.

One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?

输入格式:
Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 1 0 6 10^{6} 106 .

输出格式:
Output the maximum possible length of a regular bracket sequence.

可以用栈,代码如下:

#include <iostream>
using namespace std;

const int N = 1e6 + 10;
char s[N], stk[N];
int top;

int main() {
  scanf("%s", s);

  int res = 0;
  for (int i = 0; s[i]; i++)
    if (s[i] == '(') stk[top++] = '(';
    else if (top && stk[top - 1] == '(') top--, res += 2;
  
  printf("%d\n", res);
}

时空复杂度 O ( n ) O(n) O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值