Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes beautiful.
Below there was also written that a string is called beautiful if for each i (1 ≤ i ≤ |s|) there are no more ')' characters than '(' characters among the first i characters of s and also the total number of '(' characters is equal to the total number of ')' characters.
Help Malek open the door by telling him for each '#' character how many ')' characters he must replace it with.
The first line of the input contains a string s (1 ≤ |s| ≤ 105). Each character of this string is one of the characters '(', ')' or '#'. It is guaranteed that s contains at least one '#' character.
If there is no way of replacing '#' characters which leads to a beautiful string print - 1. Otherwise for each character '#' print a separate line containing a positive integer, the number of ')' characters this character must be replaced with.
If there are several possible answers, you may output any of them.
(((#)((#)
1 2
()((#((#(#()
2 2 1
#
-1
(#)
-1
|s| denotes the length of the string s.
题意:给一个字符串,#可以替代成至少一个 ‘)’,问是否可以组成合法的字符串,使得左右括号数目相等,且合法对应。如果可以的话,输出每个#替代成几个右括号。
思路:首先判断最后一个#后面的是否合法,且最后会剩下几个右括号,然后从左到右搜,每次先把#换成一个右括号,最后一个#换成剩下需要的即可。
AC代码如下:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
char s[100010];
int val[100010],num;
void solve()
{
int T,t,n,i,j,k,a=0,m=0,pos,b=0;
bool flag=true;
scanf("%s",s+1);
num=0;
n=strlen(s+1);
for(i=1;i<=n;i++)
if(s[i]=='#')
{
num++;
pos=i;
}
for(i=n;i>pos;i--)
{
if(s[i]==')')
b++;
else
b--;
if(b<0)
flag=false;
}
if(!flag)
{
printf("-1\n");
return;
}
//printf("b %d\n",b);
for(i=1;i<=pos;i++)
{
if(s[i]=='(')
a++;
else if(s[i]==')')
a--;
else
{
m++;
if(m!=num)
{
val[m]=1;
a--;
}
else
{
if(a-b>=1)
{
val[m]=a-b;
a=0;
}
else
flag=false;
}
}
if(a<0)
{
flag=false;
break;
}
//printf("a %d \n",a);
}
if(!flag)
{
printf("-1\n");
}
else
for(i=1;i<=num;i++)
printf("%d\n",val[i]);
}
int main()
{
solve();
}