Codeforces Round #551 (Div. 2) C. Serval and Parenthesis Sequence ###K ###K ###K //K
题目链接:https://codeforces.ml/contest/1153/problem/C
题意:给定一段字符串 由"(" 和")"和"?"组成, ?里面可以填"(" 或者")" 是否存在 字符串的任意前缀都不是合法 但整个序列是合法序列 (()) 这种为合法
思路:这种构造题 根据时间复杂度 不是枚举所有的解 就是 用贪心之类的得到一种最优解满足所有情况 这道题显然是后者
自己做的时候想法是 尽量让( 先多,这样可以更好的避免前面的合法 判断只需要判断前面没有<=0的情况 n的时候要等于0 即满足
题解给的是 假设( 为1 )为-1 要在前面避免sum<=0的情况, 那么贪心就应该让sum前面尽量的大,所以能填(的都填 ( 后面的填 )即可
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn=3e5+10; 4 const int mod=1e9+7; 5 #define ll long long 6 #define ull unsigned long long 7 #define pi pair<int,int> 8 #define fi first 9 #define sc second 10 #define pb push_back 11 12 char s[maxn]; 13 14 15 int main() 16 { 17 ios::sync_with_stdio(false); 18 cin.tie(0); 19 int n; 20 cin>>n>>(s+1); 21 int cnt=0; 22 for(int i=1;i<=n;i++) 23 { 24 if(s[i]=='(') cnt++; 25 } 26 if(n%2||cnt>n/2) 27 { 28 cout<<":("<<'\n'; 29 return 0; 30 } 31 int num=n/2-cnt; 32 for(int i=1;i<=n;i++) 33 { 34 if(s[i]!='?') continue; 35 if(num) s[i]='(',num--; 36 else s[i]=')'; 37 } 38 int f=0,sum=0; 39 for(int i=1;i<=n;i++) 40 { 41 if(s[i]=='(') sum++; 42 else sum--; 43 if(i!=n&&sum<=0) f=1; 44 } 45 if(sum) f=1; 46 if(f) cout<<":("<<'\n'; 47 else cout<<(s+1)<<'\n'; 48 49 50 51 }

浙公网安备 33010602011771号