C. Bracket Subsequence(括号匹配+思维)

本文介绍了一个算法问题,即从给定的合法括号序列中找到长度为k的子序列,该子序列同样为合法括号序列。文章给出了具体的解决思路与实现代码。

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

C. Bracket Subsequence

http://codeforces.com/contest/1023/problem/C

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.

Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

You are given a regular bracket sequence s

and an integer number k. Your task is to find a regular bracket sequence of length exactly k such that it is also a subsequence of s

.

It is guaranteed that such sequence always exists.

Input

The first line contains two integers n

and k (2≤k≤n≤2⋅105, both n and k are even) — the length of s

and the length of the sequence you are asked to find.

The second line is a string s

— regular bracket sequence of length n

.

Output

Print a single string — a regular bracket sequence of length exactly k

such that it is also a subsequence of s

.

It is guaranteed that such sequence always exists.

Examples

Input

Copy

6 4
()(())

Output

Copy

()()

Input

Copy

8 8
(()(()))

Output

Copy

(()(()))

题意:以为跟运算顺序还有关呢。后来发现前边说的都是废话。就是求一个长为m的合法子串。

思路:就是一个左括号匹配一个右括号。我们先不去想他是怎么去的,我们就想先保留。

假设遇到了一个左括号,那么括号数就+1,遇到一个右括号就暂时保留(为了保存原来括号的顺序)然后等到括号数等于m/2的时候就不用再找了,缺几个右括号直接在后边填上(认真想想对不对)

代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    string s;
    int n,m,lala,haha;
    scanf("%d%d",&n,&m);
    lala=0;
    haha=0;
    cin>>s;
    for(int i=0;i<n;i++){
        if(s[i]=='(')
            lala++;
        else
            haha++;
        cout<<s[i];
        if(lala==m/2)
            break;
    }
    for(int i=haha+1;i<=m/2;i++){
        cout<<")";
    }
    cout<<endl;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值