2020年HDU多校第三场 1009 Parentheses Matching(栈)
题意:给字符串由(,),*组成,要求如下
1,括号匹配;
2,长度最短;
3,字典序最小;
操作将*去掉,或者变成)或(。
题解:明显可以用栈把匹配的括号先去掉,剩下不匹配的用 * 去补,将余下的" ) "从前往后尽量变前面的 * 为" ( ",(从前往后遍历保证" ( "尽可能在每个" ) "的前面,变前面的 * 是使字典序尽可能小),余下的" ( ",相反操作即可。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<stack>
using namespace std;
int t,lin,len;
char s[100007];
vector<int>ho,pre,re;
stack<pair<int,int>>sa;
pair<int,int>now;
void init(){
ho.clear();
pre.clear();
re.clear();
}
int main(){
scanf("%d",&t);
while(t--){
init();
scanf("%s",s);
len=strlen(s);
for(int i=0;i<len;i++){
if(s[i]=='*'){
ho.push_back(i);
}
else{
if(sa.empty()){
sa.push({i,s[i]-'('});
}
else{
now=sa.top();
if(now.second==0&&s[i]==')'){
sa.pop();
}
else{
sa.push({i,s[i]-'('});
}
}
}
}
while(!sa.empty()){
if(sa.top().second==0){
pre.push_back(sa.top().first);
}
else{
re.push_back(sa.top().first);
}
sa.pop();
}
reverse(re.begin(),re.end());
int r=ho.size()-1,l=0,ok=1;
for(int i=0;i<re.size();i++){
if(l<=r&&ho[l]<re[i]){
s[ho[l]]='(';
l++;
}
else{
ok=0;
}
}
for(int i=0;i<pre.size();i++){
if(l<=r&&ho[r]>pre[i]){
s[ho[r]]=')';
r--;
}
else{
ok=0;
}
}
if(!ok){
printf("No solution!\n");
}
else{
for(int i=0;i<len;i++){
if(s[i]=='('||s[i]==')'){
printf("%c",s[i]);
}
}puts("");
}
}
}