Codeforces 1023C Bracket Subsequence(瞎搞)

题目链接:Bracket Subsequence

题意

给定一个长度为 n n 的合法括号序列,其中的左右括号能完全匹配,要求从中找到一个长度为 k 的合法括号子序列。

输入

第一行为两个整数 n,k (2kn2×105) n , k   ( 2 ≤ k ≤ n ≤ 2 × 10 5 ) ,其中 n n k 都是偶数,第二行为一个长度为 n n 的字符串,字符串保证是一个合法的括号序列。

输出

输出长度为 k 的合法括号子序列。

样例

输入
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值