#include <iostream>
#include <string>
#include <cstdint>
#include <tuple>
#include <algorithm>
typedef std::tuple<std::uint64_t, std::uint64_t> RData;
bool ErasePairOne(std::string& S) {
std::size_t i = 0;
std::size_t j = 0;
for (i = 0; i < S.size(); i++) {
if (S[i] == '(')break;
}
for (j = i; j < S.size(); j++) {
if (S[j] == ')')break;
}
if (j == S.size())return false;
S.erase(S.begin() + j);
S.erase(S.begin() + i);
return true;
}
bool LTurnEraseOneL(std::string& S) {
auto it = std::find(S.begin(), S.end(), '(');
if (it == S.end())return false;
*it = ')';
return ErasePairOne(S);
}
bool LTurnEraseOneR(std::string& S) {
auto it = std::find(S.rbegin(), S.rend(), '(');
if (it == S.rend())return false;
*it = ')';
return ErasePairOne(S);
}
bool RTurnEraseOneL(std::string& S) {
auto it = std::find(S.begin(), S.end(), ')');
if (it == S.end())return false;
*it = '(';
return ErasePairOne(S);
}
bool RTurnEraseOneR(std::string& S) {
auto it = std::find(S.rbegin(), S.rend(), ')');
if (it == S.rend())return false;
*it = '(';
return ErasePairOne(S);
}
bool PairTurnEraseOne(std::string& S) {
std::size_t i = 0;
std::size_t j = 0;
for (i = 0; i < S.size(); i++) {
if (S[i] == ')')break;
}
for (j = i; j < S.size(); j++) {
if (S[j] == '(')break;
}
if (j == S.size())return false;
S[i] = '(';
S[j] = ')';
return ErasePairOne(S);
}
std::int64_t MakeHoge(std::string S) {
std::uint64_t C = 0;
std::string B = S;
bool F = true;
while (ErasePairOne(S));
B = S;
do {
F = false;
while (LTurnEraseOneL(S))
{
C++;
B = S;
}
S = B;
while (LTurnEraseOneR(S))
{
C++;
B = S;
}
S = B;
while (RTurnEraseOneL(S))
{
C++;
B = S;
}
S = B;
while (RTurnEraseOneR(S))
{
C++;
B = S;
}
S = B;
while (PairTurnEraseOne(S))
{
C += 2;
B = S;
}
S = B;
} while (S.size()>1);
if (S.size() != 0)return -1;
return C;
}
/** /
std::int64_t MakeHoge(const std::string& S) {
std::string St;
std::uint64_t C = 0;
for (auto& o : S) {
if (o == '(') {
St.push_back(o);
}
if (o == ')') {
if (St.size() != 0) {
St.pop_back();
}
else {
C++;
}
}
}
C += St.size();
if (C % 2 == 1) return -1;
return C/2;
}
*/
/** /
RData countKakko(const std::string& S) {
std::uint64_t L = 0;
std::uint64_t R = 0;
for (auto& o : S) {
if (o == '(') L++;
if (o == ')')R++;
}
return{ L,R };
}
std::int64_t MakeHoge(const std::string& S) {
std::int64_t L = 0;
std::int64_t R = 0;
std::uint64_t c = 0;
std::tie(L, R) = countKakko(S);
if (L < R) std::swap(L, R);
while (!(L <= R)) {
c++;
L--;
R++;
}
return L == R ? c : -1;
}
/**/
bool Show(const std::string& S, std::int64_t N) {
std::cout << S << " -> " << N << std::endl;
return true;
}
int main() {
std::string S;
std::int64_t R = 0;
S = ")";
R = MakeHoge(S);
Show(S, R);
S = "())())";
R = MakeHoge(S);
Show(S, R);
S = ")()()(";
R = MakeHoge(S);
Show(S, R);
S = ")))(((";
R = MakeHoge(S);
Show(S, R);
S = "(())())((())(()(";
R = MakeHoge(S);
Show(S, R);
S = "())((())()))()(((()))()((((((((()()(()))";
R = MakeHoge(S);
Show(S, R);
return 0;
}