답안 #341612

# 제출 시각 아이디 문제 언어 결과 실행 시간 메모리
341612 2020-12-30T08:39:56 Z phathnv 괄호 문자열 (CEOI16_match) C++11
0 / 100
1 ms 364 KB
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int N = 1e5 + 1;
const int AL = 26;

int n, match[N], pre[N][AL];
string s;

void readInput(){
    cin >> s;
    n = s.size();
    s = '*' + s;
}

void optimize(int l, int r){
    if (l > r)
        return;
    //cerr << "opt " << l << ' ' << r << endl;
    for(int tmp = l; tmp < r; tmp = match[tmp] + 1)
        optimize(tmp + 1, match[tmp] - 1);
    while (l < r && match[l] != r){
        int tmp = pre[r][s[l] - 'a'];
        if (tmp > match[l]){
            optimize(tmp + 1, r);
            r = tmp;

            int mL = match[l];
            int mR = match[r];
            match[l] = r;
            match[r] = l;
            match[mL] = mR;
            match[mR] = mL;
            optimize(l + 1, r - 1);
            return;
        } else {
            l = match[l] + 1;
        }
    }
}

void solve(){
    stack <int> st;
    for(int i = 1; i <= n; i++){
        if (st.empty()){
            st.push(i);
        } else if (s[st.top()] == s[i]){
            match[st.top()] = i;
            match[i] = st.top();
            st.pop();
            for(int j = 0; j < AL; j++)
                pre[i][j] = pre[match[i] - 1][j];
            pre[i][s[i] - 'a'] = i;
        } else {
            st.push(i);
        }
    }
    if (!st.empty()){
        cout << -1;
        return;
    }

    optimize(1, n);

    for(int i = 1; i <= n; i++)
        cout << (match[i] > i? '(' : ')');
}

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    readInput();
    solve();
    return 0;
}
# 결과 실행 시간 메모리 Grader output
1 Correct 1 ms 364 KB Output is correct
2 Incorrect 1 ms 364 KB Output isn't correct
3 Halted 0 ms 0 KB -
# 결과 실행 시간 메모리 Grader output
1 Correct 1 ms 364 KB Output is correct
2 Incorrect 1 ms 364 KB Output isn't correct
3 Halted 0 ms 0 KB -
# 결과 실행 시간 메모리 Grader output
1 Correct 1 ms 364 KB Output is correct
2 Incorrect 1 ms 364 KB Output isn't correct
3 Halted 0 ms 0 KB -