#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define all(a) (a).begin(), (a).end()
#define endl '\n'
#define forn(i, l, n) for (int i = l; i < int(n); i++)
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<int, int> pii;
const int INF = 1e9 + 7;
int op = 0, cl = 0;
string solve(string str, int pos, int test, string ans, stack<char> st, int o)
{
if (pos >= str.length() && test == 0)
return ans;
if (pos >= str.length())
return "";
if (test < 0)
return "";
if (st.empty())
{
ans += "(";
st.push(str[pos]);
return solve(str, pos + 1, test + 1, ans, st, o + 1);
}
if (st.top() != str[pos])
{
ans += "(";
st.push(str[pos]);
return solve(str, pos + 1, test + 1, ans, st, o + 1);
}
else
{
string a = "";
if (o < op / 2 || 1)
{
st.push(str[pos]);
a = solve(str, pos + 1, test + 1, ans + "(", st, o + 1);
st.pop();
}
st.pop();
string b = solve(str, pos + 1, test - 1, ans + ")", st, o);
if (a.size() || b.size())
{
if (a.size())
return a;
else
return b;
}
else
return "";
}
}
int main() // Ale C.
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// freopen("output.txt", "w", stdout);
string str;
cin >> str;
for (char c : str)
{
if (c == '(')
op++;
else
cl++;
}
if (op % 2 != 0 || cl % 2 != 0)
{
cout << -1;
return 0;
}
string ans = solve(str, 0, 0, "", stack<char>(), 0);
cout << (ans.length() ? ans : "-1");
return 0;
}
Compilation message
match.cpp: In function 'std::string solve(std::string, int, int, std::string, std::stack<char>, int)':
match.cpp:18:11: warning: comparison of integer expressions of different signedness: 'int' and 'std::__cxx11::basic_string<char>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
18 | if (pos >= str.length() && test == 0)
| ~~~~^~~~~~~~~~~~~~~
match.cpp:20:11: warning: comparison of integer expressions of different signedness: 'int' and 'std::__cxx11::basic_string<char>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
20 | if (pos >= str.length())
| ~~~~^~~~~~~~~~~~~~~
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
212 KB |
Output is correct |
2 |
Correct |
3 ms |
212 KB |
Output is correct |
3 |
Correct |
0 ms |
212 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
212 KB |
Output is correct |
2 |
Correct |
3 ms |
212 KB |
Output is correct |
3 |
Correct |
0 ms |
212 KB |
Output is correct |
4 |
Execution timed out |
2084 ms |
3336 KB |
Time limit exceeded |
5 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
212 KB |
Output is correct |
2 |
Correct |
3 ms |
212 KB |
Output is correct |
3 |
Correct |
0 ms |
212 KB |
Output is correct |
4 |
Execution timed out |
2084 ms |
3336 KB |
Time limit exceeded |
5 |
Halted |
0 ms |
0 KB |
- |