题目链接:Bracket Subsequence
题意
给定一个长度为 n n 的合法括号序列,其中的左右括号能完全匹配,要求从中找到一个长度为 的合法括号子序列。
输入
第一行为两个整数 n,k (2≤k≤n≤2×105) n , k ( 2 ≤ k ≤ n ≤ 2 × 10 5 ) ,其中 n n 和 都是偶数,第二行为一个长度为 n n 的字符串,字符串保证是一个合法的括号序列。
输出
输出长度为 的合法括号子序列。
样例
输入 |
---|
6 4()(()) |
输出 |
()() |
输入 |
---|
8 8(()(())) |
输出 |
(()(())) |
题解
用栈模拟括号匹配的过程,其中弹出栈的必然是合法的括号序列,将弹出栈的括号下标标记,当弹出栈的括号个数达到 k k <script type="math/tex" id="MathJax-Element-8">k</script> 时,将所有标记的括号输出。
过题代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <cmath>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <algorithm>
using namespace std;
#define LL long long
const int maxn = 200000 + 100;
int n, k, top;
char str[maxn];
bool vis[maxn];
int sta[maxn];
int main() {
#ifdef Dmaxiya
freopen("test.txt", "r", stdin);
// freopen("10.out", "w", stdout);
#endif // Dmaxiya
while(scanf("%d%d", &n, &k) != EOF) {
top = 0;
memset(vis, 0, sizeof(vis));
scanf("%s", str);
for(int i = 0; i < n; ++i) {
if(str[i] == '(') {
sta[top++] = i;
} else {
--top;
vis[sta[top]] = true;
vis[i] = true;
k -= 2;
if(k == 0) {
break;
}
}
}
for(int i = 0; i < n; ++i) {
if(vis[i]) {
printf("%c", str[i]);
}
}
printf("\n");
}
return 0;
}