#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
int main() {
ifstream fin("match.in");
ofstream fout("match.out");
string s;
fin >> s;
int n = s.length();
if (n % 2 != 0) {
fout << -1 << endl;
return 0;
}
// Собираем позиции для каждого символа
vector<vector<int>> positions(26);
for (int i = 0; i < n; i++) {
positions[s[i] - 'a'].push_back(i);
}
// Проверяем четность
for (int i = 0; i < 26; i++) {
if (positions[i].size() % 2 != 0) {
fout << -1 << endl;
return 0;
}
}
// Строим пары: для каждого символа соединяем i-ю позицию с (i + m/2)-й позицией
vector<int> pair(n, -1);
for (int c = 0; c < 26; c++) {
int m = positions[c].size();
for (int i = 0; i < m / 2; i++) {
int open_idx = positions[c][i];
int close_idx = positions[c][i + m / 2];
pair[open_idx] = close_idx;
pair[close_idx] = open_idx;
}
}
// Проверяем, что пары образуют правильную скобочную последовательность
stack<int> st;
for (int i = 0; i < n; i++) {
if (pair[i] > i) {
// Это открывающая скобка (пара находится правее)
st.push(i);
} else {
// Это закрывающая скобка
if (st.empty() || pair[st.top()] != i) {
fout << -1 << endl;
return 0;
}
st.pop();
}
}
if (!st.empty()) {
fout << -1 << endl;
return 0;
}
// Строим результат
string result(n, ' ');
for (int i = 0; i < n; i++) {
if (pair[i] > i) {
result[i] = '(';
} else {
result[i] = ')';
}
}
fout << result << endl;
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... |