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>
#define ll long long
using namespace std;
#define f first
#define s second
#define pb push_back
#define ep emplace
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define uniquev(v) sort(all(v)), (v).resize(unique(all(v)) - (v).begin())
#define mem(f,x) memset(f , x , sizeof(f))
#define sz(x) (int)(x).size()
#define __lcm(a, b) (1ll * ((a) / __gcd((a), (b))) * (b))
#define mxx *max_element
#define mnn *min_element
#define cntbit(x) __builtin_popcountll(x)
#define len(x) (int)(x.length())
const int N = 1e5 + 10;
int n;
bool check(string s) {
stack <char> st;
for (int i = 1; i <= n; i++) {
if (st.empty() || (st.top() != s[i])) {
st.push(s[i]);
} else {
st.pop();
}
}
return st.empty();
}
vector <ll> coor;
vector <int> pos[N];
ll p[N], mod = 1e11 + 7, base = 37;
char tt[N];
int sp[N][30];
string s;
void dnc(int l, int r) {
if (l >= r)
return;
int m = (sp[r][s[l] - 'a']);
if (s[l] == s[r]) {
m = r;
}
tt[l] = '(';
tt[m] = ')';
dnc(l + 1, m - 1);
dnc(m + 1, r);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
p[0] = 1;
for (int i = 1; i < N; i++) {
p[i] = (p[i - 1] * base) % mod;
}
cin >> s;
s = '0' + s;
n = len(s) - 1;
if (check(s) == 0) {
cout << -1 << '\n';
return 0;
}
stack <char> st;
ll all = 0;
coor.pb(all);
for (int i = 1; i <= n; i++) {
if (st.empty() || (st.top() != s[i])) {
st.push(s[i]);
all = (all + p[sz(st)] * (ll)(st.top() - 'a' + 1));
} else {
all = (all - p[sz(st)] * (ll)(st.top() - 'a' + 1));
st.pop();
}
while (all < 0)
all += mod;
while (all >= mod)
all -= mod;
coor.pb(all);
}
uniquev(coor);
all = 0;
while (sz(st))
st.pop();
for (int i = 1; i <= n; i++) {
if (st.empty() || (st.top() != s[i])) {
st.push(s[i]);
all = (all + p[sz(st)] * (ll)(st.top() - 'a' + 1));
} else {
all = (all - p[sz(st)] * (ll)(st.top() - 'a' + 1));
st.pop();
}
while (all < 0)
all += mod;
while (all >= mod)
all -= mod;
int t = lower_bound(all(coor), all) - coor.begin();
pos[t].pb(i);
}
for (int i = 0; i <= n; i++) {
vector <int> st(30, 0);
for (auto x : pos[i]) {
for (int j = 0; j < 26; j++) {
sp[x][j] = st[j];
}
st[s[x] - 'a'] = x;
}
}
dnc(1, n);
for (int i = 1; i <= n; i++)
cout << tt[i];
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... |