CF1153C Serval and Parenthesis Sequence

思路:

贪心,参考了https://codeforces.com/blog/entry/66539

实现:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int main()
 4 {
 5     int n; string s;
 6     while (cin >> n >> s)
 7     {
 8         if (n & 1) { cout << ":(" << endl; continue; }
 9         int l = 0;
10         for (int i = 0; i < n; i++)
11         {
12             if (s[i] == '(') l++;
13         }
14         if (l > n / 2) { cout << ":(" << endl; continue; }
15         for (int i = 0; i < n; i++)
16         {
17             if (l == n / 2) break;
18             else if (s[i] == '?') { s[i] = '('; l++; }
19         }
20         for (int i = 0; i < n; i++)
21         {
22             if (s[i] != '(') s[i] = ')';
23         }
24         l = 0; bool flg = true;
25         for (int i = 0; i < n; i++)
26         {
27             if (s[i] == '(') l++;
28             else
29             {
30                 l--;
31                 if (l < 0 || (l == 0 && i != n - 1)) { flg = false; break; }
32             }
33         }
34         if (l) flg = false;
35         cout << (flg ? s : ":(") << endl;
36     }
37     return 0;
38 }
原文地址:https://www.cnblogs.com/wangyiming/p/10776755.html