跳到正文

剪贴板

剪贴板 0211yfyf

原文
剪贴板信息

剪贴板信息

收录
更新
C++
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ll;
const ll N = 1e5 + 5, B = 131;
ll n, h[N], d[N], e[N];
char ans[N];
vector<int> v[N];
string s;
struct node{char c; ll x;};
stack<node> st;
void dfs(int l, int r) {
	if (l > r) return;
	ans[l] = '(';
	int w = upper_bound(v[h[l]].begin() + e[l] + 1, v[h[l]].end(), r - 1) - v[h[l]].begin();
	--w; int pos = v[h[l]][w] + 1;
	ans[pos] = ')';
	dfs(l + 1, pos - 1); dfs(pos + 1, r);
}
int main() {
	ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
	cin >> s; n = s.size(); s = "." + s + ".";
	for (int i = 1; i <= n; ++i) {
		if (!st.empty()) {
			if (st.top().c == s[i]) st.pop();
			else {
				ll t = st.top().x * B + s[i];
				node tmp; tmp.c = s[i], tmp.x = t;
				st.push(tmp);
			}
		} else {
			node tmp; tmp.c = s[i], tmp.x = s[i];
			st.push(tmp);
		}
		if (st.empty()) h[i] = 0;
		else h[i] = st.top().x;
		d[i] = h[i];
	}
	if (!st.empty()) {cout << -1 << endl; return 0;}
	sort(d + 1, d + n + 1); 
	int p = unique(d + 1, d + n + 1) - (d + 1);
	for (int i = 1; i <= n; ++i) {
		h[i] = lower_bound(d + 1, d + p + 1, h[i]) - d;
		v[h[i]].push_back(i);
		e[i] = v[h[i]].size() - 1;
	}
	dfs(1, n);
	for (int i = 1; i <= n; ++i) cout << ans[i];
	cout << endl;
	return 0;
}