Codeforces1153C Serval and Parenthesis Sequence 字符串模拟括号匹配 1600

https://codeforces.com/contest/1153/problem/C
由(,),?组成字符串 将所有?替换后 使得所有字符串前缀子串不匹配 但整个字符串括号匹配
如果n为奇数 不匹配
n为偶数 如果某个(或)超过整个长度一半,就算另一个全部替换也不能匹配
n为偶数 也未超过长度一半 优先替换?为左括号最终(出现半 保证前缀尽量不合法,其余?替换)
特例 )优先于(出现 使得查找时cnt为- 不合法 )(??
()((??
提前匹配 cnt=0 i!=n-1 不合法

#include<iostream>
#include<cstdio>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define mp make_pair
#define fi first
#define se second
const double PI=acos(-1.0);
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

const ll inf=0x3f3f3f3f3f3f3f3f;
const int INF=0x3f3f3f3f; 
const ll mod=1e9+7;
const int maxn=2e5+5;
ll gcd(ll a,ll b){return b!=0?gcd(b,a%b):a;}
ll pow_mod(ll a,ll b){ll res=1;while(b!=0){if(b&1)res=res*a%mod;b>>=1;a=a*a%mod;}return res;}
ll inv_mod(ll a){return pow_mod(a,mod-2);}
//o(n)实现 一次加到位 
int n,t;

int main()
{
	IO;
	string s;
	int l=0,r=0;
	cin>>n;
	cin>>s;
	if(n&1)	//奇数何谈pp 
		return puts(":("),0;
	for(int i=0;i<n;i++)
	{
		if(s[i]=='(')
			l++;
		else if(s[i]==')')
			r++;
	}
	if(l>n/2 || r>n/2)//是偶数 一半一半 有?超过1半另一个替换?也没办法 
		return puts(":("),0;
	l=n/2-l;
	for(int i=0;i<n;i++)
	{
		if(l>0 && s[i]=='?')
		{
			s[i]='(';
			l--;
		}
		else if(l==0 && s[i]=='?')
		{
			s[i]=')';
		}
	}
	//??((??
	//(?((??
	//()(())
	int cnt=0;
	for(int i=0;i<n;i++)
	{
		if(s[i]=='(')//((?(??)? (((())))
			cnt++;
		else
			cnt--;
		if(cnt==0 && i!=n-1)
			return puts(":("),0;	//提前pp 
		if(cnt<0)
			return puts(":("),0;//右括号先出现 )??) )(()
	}
	cout<<s<<endl;
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_40423146/article/details/89337440