题目链接:
http://codeforces.com/problemset/problem/494/A
解题思路:
Codeforces官方题解:
Consider a string consisting of '(' and ')' characters. Let's build the following sequence from this string:
-
a0 = 0
-
for each 1 ≤ i ≤ |s| ai = ai - 1 + 1 if si = '(' and ai = ai - 1 - 1 otherwise. (The string is considered as 1-based index).
It can be proven that a string is beautiful if the following conditions are satisfied:
-
for each 0 ≤ i ≤ |s| ai ≥ 0.
-
a|s| = 0
Using the above fact we can prove that if in a beautiful string we remove a ')' character and put it further toward the end of the string the resulting string is beautiful as well. These facts leads us to the following fact: if we can move a ')' character further toward the end of string it is better if we'd do it. This yields the following greedy solution:
We'll first put exactly one ')' character at each '#' character. Then we'll build the sequence we described above. if the first condition isn't satisfied then there is no way that leads to a beautiful string. So the answer is -1. Otherwise we must put exactly a|s| more ')' characters in the place of last '#' character. Then if this string is beautiful we'll print it otherwise the answer is -1.
AC代码:
#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
using namespace std;
int main()
{
string str;
while(cin>>str)
{
vector<int>vec;
vec.clear();
bool flag = true;
int lp=0,rp=0,index,l=str.size();
for(int i=0;i<str.size();i++)
if(str[i]=='#')
index = i;
for(int i=0;i<index;i++)
{
if(str[i]=='#')
{
vec.push_back(1);
str[i]=')';
}
}
lp=rp=0;
for(int i=0;i<str.size();i++)
{
if(str[i]=='(')
lp++;
else
if(str[i]==')')
rp++;
}
string mak=")",fina="";
for(int i=0;i<lp-rp-1;i++)
mak+=')';
vec.push_back(lp-rp);
for(int i=0;i<str.size();i++)
{
if(str[i]=='#')
fina+=mak;
else
fina+=str[i];
}
lp=rp=0;
// cout<<fina<<endl;
for(int i=0;i<fina.size();i++)
{
if(fina[i]==')')
rp++;
else
lp++;
if(rp>lp)
flag=false;
}
if(flag)
{
for(int i=0;i<vec.size();i++)
printf("%d\n",vec[i]);
}
else
printf("-1\n");
}
return 0;
}