This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
class trie {
private:
struct trie_node {
trie_node *parent;
vector<trie_node*> children;
vector<int> val;
} *cur;
string s;
public:
trie() {
cur = new trie_node{nullptr, vector<trie_node*>(26, nullptr), vector<int>(26, -1)};
s = "";
}
void update(char c, int x) {
cur->val[c - 'a'] = x;
}
int query(char c) {
return cur->val[c - 'a'];
}
void go_up() {
cur = cur->parent;
s.pop_back();
}
void go_down(char c) {
if (cur->children[c - 'a'] == nullptr) cur->children[c - 'a'] = new trie_node{cur, vector<trie_node*>(26, nullptr), vector<int>(26, -1)};
cur = cur->children[c - 'a'];
s.push_back(c);
}
const char current_char() {
if (cur->parent == nullptr) return '$';
return s.back();
}
};
int n;
string s;
vector< vector<int> > prev_l;
string solve(int l, int r) {
if (l > r) return "";
if (l + 1 == r) return "()";
return "(" + solve(l + 1, prev_l[r][s[l] - 'a'] - 1) + ")" + solve(prev_l[r][s[l] - 'a'] + 1, r);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> s;
int n = (int) s.length();
trie mp;
prev_l.assign(n, vector<int>(26, -1));
for (int i = 0; i < n; i++) {
if (mp.current_char() == s[i]) mp.go_up();
else mp.go_down(s[i]);
mp.update(s[i], i);
for (int j = 0; j < 26; j++) prev_l[i][j] = mp.query(j + 'a');
}
if (mp.current_char() != '$') cout << -1 << '\n';
else cout << solve(0, n - 1) << '\n';
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |