题目地址:
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)。