题目链接:http://codeforces.com/contest/1023/problem/C
题意是输入n,m,然后输入长度为n的一个括号序列,对这个括号序列操作,删除任意的括号对,使这个序列长度为m,然后将其输出,输出的括号序列中的括号必须是配对的,不会有)(这种存在。
这个题差不多就是一个括号配对的问题,我看了别人的代码,基本上都是用数组去模拟的,我是用stack去写的,我大概说一下我的写法。首先要知道第一个)肯定是和它左边离它最近的(配对的,所以用了stack去存(,当遇到了)的时候,把离)最近的( pop出去,这就相当于删除掉了一对括号,然后删除完了就让m+2,直到n等于m为止,然后将stack里的括号都输出出来,剩下的按原顺序输出。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
int n,m;
string str;
char ch;
stack<char> s;
int main()
{
cin>>n>>m;
if(n == m){
cin>>str;
cout<<str<<endl;
return 0;
}
int i,flag = 0;
for(i=0;i<n;i++){
cin>>ch;
if(ch == '('){
s.push(ch);
}
if(ch == ')'){
s.pop();
m += 2;
}
if(m == n){
while(!s.empty()){
cout<<s.top();
s.pop();
}
for(int j=i+1;j<m;j++){
cin>>ch;
cout<<ch;
}
cout<<endl;
return 0;
}
}
return 0;
}