Problem Description
Given a string P consisting of only parentheses and asterisk characters (i.e. “(”, “)” and “"), you are asked to replace all the asterisk characters in order to get a balanced parenthesis string with the shortest possible length, where you can replace each "” by one “(”, or one “)”, or an empty string “”.
A parenthesis string S is a string consisting of only parentheses (i.e. “(” and “)”), and is considered balanced if and only if:
● S is an empty string, or
● there exist two balanced parenthesis strings A and B such that S=AB, or
● there exists a balanced parenthesis string C such that S=(C).
For instance, “”, “()”, “(())”, “()()”, “()(())” are balanced parenthesis strings.
Due to some notorious technical inability, if there are several solutions with the shortest possible length, then you have to report the smallest possible one in lexicographical order.
For every two different strings A and B of the same length n, we say A is smaller than B in lexicographical order if and only if there exists some integer k such that:
● 1≤k≤n, and
● the first (k−1) characters of A and that of B are exactly the same, and
● the k-th character of A is smaller than that of B.
For instance, “()(())” is smaller than “()()()”, and in this case, k=4.
Input
There are several test cases.
The first line contains an integer T (1≤T≤105), denoting the number of test cases. Then follow all the test cases.
For each test case, the only line contains a string of length n (1≤n≤105), denoting the string P that consists of only parentheses and asterisk characters.
It is guaranteed that the sum of n in all test cases is no larger than 5×106.
Output
For each test case, output in one line “No solution!” (without quotes) if no solution exists, or otherwise the smallest possible solution in lexicographical order. Note that the output characters are case-sensitive.
Sample Input
5
*))*)
*(*)*
*)*(*
******
((***)()((**
Sample Output
No solution!
()
()()
(())()(())
先从左往右,从右往左分别记录所需’(‘和’)‘个数。因为需要最小字典序,所以从右往左能填入’)‘就填入,之后再从左往右补上’(’,最后检查所得答案是否合法。
#include
#include
#include
#include
#include
using namespace std;
const int N=200020;
char s[N];
int n,p,l,r;
void fun1()
{
for(int i=1; i<=n; i++)
{
if(s[i]=='(') l++;
else if(s[i]==')') l=max(l-1,0);
}
for(int i=n; i>0; i--)
{
if(s[i]==')') r++;
else if(s[i]=='(') r=max(r-1,0);
}
}
void fun2()
{
for(int i=n; i>0; i--)
{
if(l==0) continue;
if(s[i]=='*')
{
s[i]=')';
l--;
}
}
for(int i=1; i<=n; i++)
{
if(r==0) continue;
if(s[i]=='*')
{
s[i]='(';
r--;
}
}
}
int check()
{
int l=0;
for(int i=1; i<=n; i++)
{
if(s[i]=='(')l++;
else if(s[i]==')')
{
if(l==0) return 0;
l--;
}
}
if(l!=0)return 0;
return 1;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%s",s+1);
n=(int)strlen(s+1);
l=0,r=0;
fun1();
fun2();
if(check()==0) printf("No solution!\n");
else
{
for(int i=1; i<=n; i++) if(s[i]!='*') printf("%c",s[i]);
puts("");
}
}
return 0;
}