Submission #539031

#TimeUsernameProblemLanguageResultExecution timeMemory
539031alextodoranMatch (CEOI16_match)C++17
100 / 100
16 ms12616 KiB
/**
 ____ ____ ____ ____ ____
||a |||t |||o |||d |||o ||
||__|||__|||__|||__|||__||
|/__\|/__\|/__\|/__\|/__\|

**/

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int N_MAX = (int) 1e5;

string S;
int N;

int maxStart[N_MAX][26];

bool exists () {
    vector <int> st;
    for (int i = 0; i < N; i++) {
        if (st.empty() == true || S[st.back()] != S[i]) {
            st.push_back(i);
        } else {
            st.pop_back();
        }
    }
    return (st.empty() == true);
}

void precalc () {
    for (int i = 0; i < (int) S.size(); i++) {
        fill(maxStart[i], maxStart[i] + 26, -1);
        maxStart[i][(char) (S[i] - 'a')] = i;
    }
    for (int i = 1; i < (int) S.size(); i++) {
        for (int c = 0; c < 26; c++) {
            int j = maxStart[i - 1][S[i] - 'a'] - 1;
            if (maxStart[i][c] == -1 && j >= 0) {
                if (S[j] == (char) ('a' + c)) {
                    maxStart[i][c] = j;
                } else {
                    maxStart[i][c] = maxStart[j][c];
                }
            }
        }
    }
}

string P;
void solve (int l, int r) {
    if (l <= r) {
        int matchl = maxStart[r][S[l] - 'a'];
        P[l] = '('; P[matchl] = ')';
        solve(l + 1, matchl - 1);
        solve(matchl + 1, r);
    }
}
void solve () {
    for (int i = 0; i < N; i++) {
        P += '?';
    }
    solve(0, N - 1);
}

int main () {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    cin >> S; N = (int) S.size();
    if (exists() == true) {
        precalc();
        solve();
        cout << P << "\n";
    } else {
        cout << -1 << "\n";
    }

    return 0;
}

Compilation message (stderr)

match.cpp: In function 'void precalc()':
match.cpp:37:21: warning: array subscript has type 'char' [-Wchar-subscripts]
   37 |         maxStart[i][(char) (S[i] - 'a')] = i;
      |                     ^~~~~~~~~~~~~~~~~~~
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...