// C++ program to find minimum number of
// reversals required to balance an expression
#include<bits/stdc++.h>
using namespace std;
// Returns count of minimum reversals for making
// expr balanced. Returns -1 if expr cannot be
// balanced.
int countMinReversals(string expr)
{
int len = expr.length();
// length of expression must be even to make
// it balanced by using reversals.
if (len%2)
return -1;
int open=0,close=0,toReverse=0;
stack<char> s;
for (int i=0; i<len; i++)
{
if (expr[i]=='{')
open++;
else
{
if (open>0)
open--;
else
{ toReverse++;
open++;
}
}
}
toReverse +=open/2;
return toReverse;
}
// Driver program to test above function
int main()
{
string expr = "}}{{";
cout << countMinReversals(expr);
return 0;
}
Ly8gQysrIHByb2dyYW0gdG8gZmluZCBtaW5pbXVtIG51bWJlciBvZgovLyByZXZlcnNhbHMgcmVxdWlyZWQgdG8gYmFsYW5jZSBhbiBleHByZXNzaW9uCiNpbmNsdWRlPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgoKLy8gUmV0dXJucyBjb3VudCBvZiBtaW5pbXVtIHJldmVyc2FscyBmb3IgbWFraW5nCi8vIGV4cHIgYmFsYW5jZWQuIFJldHVybnMgLTEgaWYgZXhwciBjYW5ub3QgYmUKLy8gYmFsYW5jZWQuCmludCBjb3VudE1pblJldmVyc2FscyhzdHJpbmcgZXhwcikKewoJaW50IGxlbiA9IGV4cHIubGVuZ3RoKCk7CgoJLy8gbGVuZ3RoIG9mIGV4cHJlc3Npb24gbXVzdCBiZSBldmVuIHRvIG1ha2UKCS8vIGl0IGJhbGFuY2VkIGJ5IHVzaW5nIHJldmVyc2Fscy4KCWlmIChsZW4lMikKCXJldHVybiAtMTsKCglpbnQgIG9wZW49MCxjbG9zZT0wLHRvUmV2ZXJzZT0wOwoJc3RhY2s8Y2hhcj4gczsKCWZvciAoaW50IGk9MDsgaTxsZW47IGkrKykKCXsKCQlpZiAoZXhwcltpXT09J3snKQoJCSAgIG9wZW4rKzsKCQllbHNlCgkJewoJCSAgICBpZiAob3Blbj4wKQoJCSAgICBvcGVuLS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