CF1153C 题解

· · 题解

洛谷传送门 & CF 传送门

思路

首先,这题中 n\bmod2=1 的情况一定不合法,可以直接特判。要尽量使所有严格前缀都不合法,则只要贪心尽量把剩余需要的 ( 往前放就行了,把 ) 往后放就行啦。最后检查一下,如果这样放还是不合法,那只能说明它无解!

代码

# include <bits/stdc++.h>
using namespace std;
int n, x, y, tot;
string a;
int main () {
    ios::sync_with_stdio (0);
    cin.tie (0);
    cout.tie (0);
    cin >> n >> a;
    if (n & 1) {
        cout << ":(";
        return 0;
    }
    x = y = n >> 1;
    for (int i = 0; i < n; ++ i)
        if (a[i] == '(')
            -- x;
        else if (a[i] == ')')
            -- y;
    for (int i = 0; i < n; ++ i)
        if (a[i] == '?')
            if (x)
                -- x, a[i] = '(';
            else
                -- y, a[i] = ')';
    for (int i = 0; i < n; ++ i)
        if (a[i] == '(')
            ++ tot;
        else if (a[i] == ')')
            if (! tot || ! (-- tot) && i < n - 1) {
                cout << ":(";
                return 0;
            }
    cout << (tot ? ":(" : a);
    return 0;
}