C. Bracket Subsequence
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 ss and an integer number kk. Your task is to find a regular bracket sequence of length exactly kksuch that it is also a subsequence of ss.
It is guaranteed that such sequence always exists.
Input
The first line contains two integers nn and kk (2≤k≤n≤2⋅1052≤k≤n≤2⋅105, both nn and kk are even) — the length of ss and the length of the sequence you are asked to find.
The second line is a string ss — regular bracket sequence of length nn.
Output
Print a single string — a regular bracket sequence of length exactly kk such that it is also a subsequence of ss.
It is guaranteed that such sequence always exists.
Examples
input
Copy
6 4 ()(())
output
Copy
()()
input
Copy
8 8 (()(()))
output
Copy
(()(()))
由于刚开始给出的字符串一定合法,所以刚开始给出的字符串一定有左括号和右括号各 n/2n/2 个。当然,我们生成的字符串也必须有 k/2k/2 个左括号和右括号。
我们可以扫描一遍原字符串,如果遇到左括号,且左括号的数量<= k/2<=k/2 ,就可以把左括号放入答案序列。
如果是右括号,我们需要确保在当前左括号数量小于右括号数量的情况下(左括号数量等于右括号的话,就不能再添加右括号了),在满足右括号数量<= k/2<=k/2 的情况下,将右括号放入答案序列。
显然,这样的做法不会破坏原来括号的相对顺序,因而这样的做法是合法的
#include <stdio.h>
char s[200005],res[200005];
int main()
{
int n,k;
scanf("%d%d",&n,&k);
scanf("%s",s);
if(n==k)printf("%s",s);
else
{
int cntl=0,cntr=0,tot=0;
for(int i=0;i<n;i++)
if(s[i]=='(')
{
if(cntl!=k/2)
{
cntl++;
res[tot++]='(';
}
}
else
{
if(cntr!=k/2&&cntl>cntr)
{
cntr++;
res[tot++]=')';
}
}
printf("%s",res);
}
return 0;
}