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的括号序列,让你删除的仅剩k/2对可以匹配的序列,输出最终结果。
题解:直接拿栈即可,首先将所有不能匹配的位置标记(一定要删除),然后在剩下的匹配对中删除多的。
使得最后剩下k/2对即可。
#include<stack>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
#define mod 1000000007
int n,k,flag[200005];
struct node
{
char s;
int id;
}s1[200005];
stack<node>t;
int main(void)
{
int num=0;
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++)
scanf(" %c",&s1[i].s),s1[i].id=i;
for(int i=1;i<=n;i++)
{
if(s1[i].s=='(')
{
t.push(s1[i]);
continue;
}
if(t.empty()==0 && t.top().s=='(')
{
t.pop();
continue;
}
flag[i]=1;num++;
}
while(t.empty()==0) flag[t.top().id]=1,t.pop(),num++;
num=n-num;
for(int i=1;i<=n;i++)
{
if(num==k || flag[i]) break;
if(s1[i].s=='(') t.push(s1[i]);
else flag[t.top().id]=1,flag[i]=1,num-=2,t.pop();
}
for(int i=1;i<=n;i++)
if(flag[i]==0)
printf("%c",s1[i].s);
printf("\n");
return 0;
}