C - Serval and Parenthesis Sequence CodeForces - 1153C
题目大意:
输入一段含有’(’,’)’,‘?’,组成的·字符串,求是否能把字符串中的’?’,替换为’(’,’)‘之一,使得最后字符串满足前缀不为正确的括号序列,但最后字符串为正确的符号序列。不能满足则输出‘:(’。
阅读理解题吧,我一直没有理解什么是严格前缀,导致最后没有做出来。理解了题意,它就是贪心了。要满足正确的括号序列,首先个数为偶数,最好正括号与反括号各一半,这就是一个贪心思路。
#include <iostream>
#include <cstdio>
#include<cstdlib>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include<time.h>
#include <stack>
#include <list>
#include <set>
#include <sstream>
#include <iterator>
using namespace std;
#define FOPI freopen("input.in", "r", stdin)
#define DOPI freopen("output.out", "w", stdout)
#define ll long long int
#define fro(i,a,n) for(ll i=a;i<n;i++)
#define pre(i,a,n) for(ll i=n-1;i>=a;i--)
#define mem(a,b) memset(a,b,sizeof(a))
#define ls l,mid,rt<<1
#define rs mid+1,r,rt<<1|1
#define fi first
#define se second
#define s_d(a) scanf("%d",&a)
#define s_lld(a) scanf("%lld",&a)
#define s_s(a) scanf("%s",a)
#define s_ch(a) scanf("%c",&a)
typedef pair<ll,ll> P;
ll gcd(ll a,ll b){return b==0?a:gcd(b,a%b);}
const double PI = 3.1415926535897932;
const double EPS=1e-6;
const int INF=0x3f3f3f3f;
const int maxn = 2e5+100;
int lowbit(int x){return x&(-x);}
int main()
{
ios::sync_with_stdio(0);
int n;
cin>>n;
string s;
cin>>s;
if(n%2==1)
cout<<":("<<endl;
else
{
int a=0,b=0;
fro(i,0,n)
{
if(s[i]=='(')
a++;
if(s[i]==')')
b++;
}
int aa=n/2-a;
int bb=n/2-b;
fro(i,0,n)
{
if(s[i]=='?')
{
if(aa)
{
s[i]='(';
aa--;
}
else
{
s[i]=')';
bb--;
}
}
}
stack<char> sta;
bool ok=0;
fro(i,0,n)
{
if(s[i]=='(')
{
sta.push(s[i]);
}
else
{
if(!sta.empty())
sta.pop();
if(sta.empty()&&i!=n-1)
{
ok=1;
//cout<<"???"<<endl;
}
}
}
if(!sta.empty())
{
ok=1;
}
if(!ok)
cout<<s<<endl;
else
cout<<":("<<endl;
}
return 0;
}