A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.

The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.

Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.

The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes $l$ nanoseconds, where $l$ is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take $2$ nanoseconds).

Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.


-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 10^6$) — the length of Dima's sequence.

The second line contains string of length $n$, consisting of characters "(" and ")" only.


-----Output-----

Print a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.


-----Examples-----
Input
8
))((())(

Output
6

Input
3
(()

Output
-1



-----Note-----

In the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is $4 + 2 = 6$ nanoseconds.

Source: codeforces | Difficulty: EASY
Tags: Greedy algorithms


Solutions:
n = int(input())
s = input()
if s.count('(') != s.count(')'):
	print(-1)
	exit()
ans = 0
ls = [0]
for i in range(n):
	if s[i] == '(':
		ls.append(ls[-1] + 1)
	else:
		ls.append(ls[-1] - 1)
ans = 0
cnt = 0
for i in range(1, n + 1):
	if ls[i] == 0:
		if cnt:
			ans += cnt + 1
		cnt = 0
	elif ls[i] < 0:
		cnt += 1
print(ans)


(n, s, p, a) = (int(input()), input(), 0, 0)
for i in s:
	if i == '(':
		p += 1
	else:
		p -= 1
		a += 2 if p < 0 else 0
print('-1' if p else a)


n = int(input())
s = input()
count = 0
res = 0
for c in s:
	if c == '(':
		count += 1
	else:
		count -= 1
		if count < 0:
			res += 2
if count != 0:
	print('-1')
else:
	print(res)


import sys
inp = sys.stdin.readline

def input():
	return inp().strip()

def iin():
	return int(input())

def lin():
	return list(map(int, input().split()))

def main():
	T = 1
	while T:
		T -= 1
		n = lin()
		a = input()
		(o, c) = ([], [])
		for (j, i) in enumerate(a):
			if i == '(':
				o.append(j)
			else:
				c.append(j)
		if len(o) != len(c):
			print(-1)
		else:
			ans = 0
			ch = 0
			ch1 = 0
			ch2 = 0
			for i in a:
				ch2 += 1
				if i == '(':
					ch += 1
				else:
					ch -= 1
				if ch < 0:
					ch1 = 1
				if ch == 0:
					if ch1:
						ans += ch2
					ch2 = 0
					ch1 = 0
			print(ans)
main()


def go():
	n = int(input())
	s = input()
	if n % 2 == 1 or s.count('(') != n // 2:
		return -1
	res = 0
	curs = 0
	prev = 0
	for ss in s:
		curs += 1 if ss == '(' else -1
		if curs == 0 and prev > 0:
			res += prev + 1
			prev = 0
		elif curs < 0:
			prev += 1
	return res
print(go())


l = int(input())
st = input()
flg1 = 0
flg2 = 0
i = 0
c = 0
for i in range(l):
	if st[i] == '(':
		flg1 = flg1 + 1
		if flg1 == 0 and flg2 == 1:
			c = c + (i - k) + 1
			flg2 = 0
	else:
		flg1 = flg1 - 1
		if flg2 == 0:
			k = i
		if flg1 < 0:
			flg2 = 1
if flg1 < 0 or flg1 > 0:
	print('-1')
else:
	print(c)


n = int(input())
s = input()
c = 0
for i in s:
	if i == '(':
		c += 1
	else:
		c -= 1
if c != 0:
	print(-1)
else:
	ans = 0
	c = 0
	j = 0
	for i in s:
		if i == ')':
			c -= 1
		else:
			c += 1
		j += 1 if c < 0 else 0
		if j > 0 and c == 0:
			ans += j + 1
			j = 0
	print(ans)


n = int(input())
s = input()
cur = 0
ans = 0
last = -1
for i in range(n):
	if s[i] == '(':
		cur += 1
		if cur == 0:
			ans += i - last
	else:
		cur -= 1
	if cur >= 0:
		last = i
if cur != 0:
	print(-1)
	exit()
print(ans)


from math import *
from collections import Counter, defaultdict, deque
from sys import stdin, stdout
input = stdin.readline
I = lambda : int(input())
M = lambda : map(int, input().split())
LI = lambda : list(map(int, input().split()))
n = I()
s = input()
ans = 0
c = 0
if n % 2:
	print(-1)
else:
	a = []
	c = 0
	for i in range(n):
		if s[i] == ')':
			if len(a) != 0 and a[-1] == '(':
				a.pop()
			else:
				a += [')']
		elif len(a) != 0 and a[-1] == ')':
			c += 2
			a.pop()
		else:
			a += ['(']
	if len(a) >= 1:
		print(-1)
	else:
		print(c)


n = int(input())
s = input()
op = 0
ans = 0
for i in s:
	if i == '(':
		op += 1
	else:
		op -= 1
		if op < 0:
			ans += 2
print(ans if op == 0 else -1)


from collections import deque, defaultdict, Counter
from bisect import bisect_left, bisect
import math

def test_case():
	n = int(input())
	s = input()
	if s.count('(') != s.count(')'):
		return -1
	count = 0
	flag = False
	last = -1
	ans = 0
	for i in range(n):
		if s[i] == '(':
			count += 1
		else:
			count -= 1
		if count == 0:
			if flag:
				ans += i - last
			last = i
			flag = False
		if count < 0:
			flag = True
	return ans
ret = test_case()
if ret != None:
	print(ret)


import sys
input = sys.stdin.readline
n = int(input())
a = input().strip()
v = 0
prev = -1
ans = 0
for i in range(n):
	if a[i] == '(':
		v += 1
	else:
		v -= 1
	if v == 0:
		if a[i] == '(':
			ans += i - prev
		prev = i
if v != 0:
	print(-1)
else:
	print(ans)


import sys

def split(word):
	return [char for char in word]

def check(string, strLen):
	countClose = 0
	countOpen = 0
	counter = 0
	isClose = False
	if string.count('(') != string.count(')'):
		return -1
	else:
		for (n, i) in enumerate(string):
			if i == '(':
				countOpen += 1
			elif i == ')':
				countClose += 1
			if countOpen == 0 and countClose == 1:
				isClose = True
			if countOpen == countClose or strLen - 1 == n:
				if isClose:
					isClose = False
					counter += countOpen
					counter += countClose
				countOpen = 0
				countClose = 0
		return counter
userInput = sys.stdin.readlines()
strLen = len(userInput[1])
string = split(userInput[1])
print(check(string, strLen))


n = int(input())
S = list(input())
d = {'(': 1, ')': -1}
c = 0
I = 0
t = 0
T = False
for i in range(n):
	if c < 0:
		T = True
	c += d[S[i]]
	if c == 0:
		if T:
			t += i - I + 1
		I = i + 1
	T = False
if c != 0:
	print(-1)
else:
	print(t)


input()
x = input()
if x.count(')') != x.count('('):
	print(-1)
else:
	cnt = 0
	n = m = 0
	for i in x:
		prev = cnt
		cnt += int(i == '(')
		cnt -= int(i == ')')
		if cnt < 0:
			n += 1
		elif cnt == 0 and prev == -1:
			n += 1
	print(n + m)


t = int(input())
s = input()
cnt1 = 0
cnt2 = 0
b = 0
a = True
mn = 0
res = 0
if t % 2 == 1:
	print(-1)
else:
	for i in range(t):
		if s[i] == ')':
			b = b - 1
			cnt1 = cnt1 + 1
		else:
			b = b + 1
			cnt2 = cnt2 + 1
		if b < 0:
			a = False
		if b == 0 and a == False:
			res = res + i - mn + 1
			mn = i + 1
			a = True
		elif b == 0:
			a = True
			mn = i + 1
	if cnt1 != cnt2:
		print(-1)
	else:
		print(res)


a = int(input())
arr = str(input())
brr = []
crr = []
summ = 0
crr.append(0)
for i in range(0, len(arr)):
	if arr[i] == '(':
		brr.append(1)
	else:
		brr.append(-1)
if sum(brr) != 0:
	print(-1)
else:
	for i in range(0, len(brr)):
		if brr[i] == 1:
			crr.append(crr[i] + 1)
		else:
			crr.append(crr[i] - 1)
	num = 0
	count = 0
	for i in range(0, len(crr) - 1):
		if crr[i] == 0:
			if crr[i + 1] == -1:
				num = num + 1
		if crr[i] < 0:
			count = count + 1
	print(num + count)


def order_brackets(s):
	opening = 0
	closing = 0
	nano = 0
	for i in s:
		if i == ')':
			if opening > 0:
				opening -= 1
			else:
				closing += 1
		elif closing > 0:
			closing -= 1
			nano += 1
		else:
			opening += 1
	if opening != closing:
		print(-1)
	else:
		print(nano * 2)
n = input()
s = input()
order_brackets(s)


from sys import stdin, stdout

def main():
	n = int(stdin.readline())
	s = stdin.readline().rstrip()
	(l, r) = (0, 0)
	for x in s:
		if x == '(':
			l += 1
		else:
			r += 1
	if l != r:
		stdout.write('-1')
		return
	a = 0
	cnt = 0
	for x in s:
		if x == '(':
			a += 1
			if a == 0:
				cnt += 1
		else:
			a -= 1
		if a < 0:
			cnt += 1
	stdout.write(str(cnt))
main()


n = int(input())
s = input()
bal = 0
start = 0
count = 0
for i in range(n):
	if s[i] == '(':
		if bal == -1:
			count += i - start + 1
		bal += 1
	else:
		if bal == 0:
			start = i
		bal -= 1
print(count if bal == 0 else -1)


import sys
input = sys.stdin.readline
N = int(input())
S = input().rstrip()
A = [0]
for s in S:
	a = 1 if s == '(' else -1
	A.append(A[-1] + a)
isOK = True
ans = 0
last0 = 0
for (i, a) in enumerate(A):
	if a == 0:
		if not isOK:
			ans += i - last0
		last0 = i
		isOK = True
	if a < 0:
		isOK = False
if A[-1] != 0:
	print(-1)
else:
	print(ans)


n = int(input())
s = input()
(openn, close, summ) = (0, 0, 0)
for i in range(n):
	if s[i] == ')':
		if openn == 0:
			close += 1
			summ += 1
		else:
			openn -= 1
	elif s[i] == '(':
		if close == 0:
			openn += 1
		else:
			close -= 1
			summ += 1
if openn == 0 and close == 0:
	print(summ)
else:
	print(-1)


from sys import stdin, exit
N = int(input())
p = input()
l = 0
r = 0
for i in p:
	if i == '(':
		l += 1
	else:
		r += 1
if l != r:
	print(-1)
	exit()
count = 0
interval = []
start = False
ans = 0
for i in range(N):
	if p[i] == '(':
		count += 1
	else:
		count -= 1
	if count < 0 and (not start):
		start = True
		be = i
	if count == 0 and start:
		interval.append((be, i))
		ans += i - be + 1
		start = False
print(ans)


import math
n = int(input())
braks = input()
s = 0
d = []
temp_len = 0
result = 0
w = False
for (index, letter) in enumerate(braks):
	if letter == '(':
		if s == 0:
			w = False
		s += 1
	else:
		if s == 0:
			w = True
		s -= 1
	if w:
		temp_len += 1
	if s == 0:
		result += temp_len
		temp_len = 0
if s != 0:
	print(-1)
else:
	print(result + temp_len)


def brackets():
	num = int(input())
	risultato = 0
	brackets = input()
	c = 0
	for i in brackets:
		if i == ')':
			c -= 1
			if c < 0:
				risultato += 2
		elif i == '(':
			c += 1
	if c != 0:
		print(-1)
	else:
		print(risultato)
brackets()


n = int(input())
a = input()
c1 = 0
c2 = 0
i = 0
ans = 0
while i < len(a):
	if a[i] == '(':
		c1 += 1
	if a[i] == ')':
		c2 += 1
	if c1 == c2:
		c1 = 0
		c2 = 0
	elif c2 > c1:
		cc1 = 0
		cc2 = 1
		j = i + 1
		while j < len(a):
			if a[j] == '(':
				cc1 += 1
			if a[j] == ')':
				cc2 += 1
			if cc1 == cc2:
				ans += j - i + 1
				c1 = 0
				c2 = 0
				i = j
				break
			j += 1
	i += 1
if c1 == c2:
	print(ans)
else:
	print(-1)


n = int(input())
s = input()
if n % 2 != 0 or s.count(')') != s.count('('):
	print(-1)
else:
	x = 0
	need = 0
	for i in range(n):
		if s[i] == '(':
			x += 1
		else:
			if x <= 0:
				need += 2
			x -= 1
	print(need)


n = input()
s = input()
if len(s) % 2 or s.count(')') != len(s) // 2:
	print(-1)
else:
	ans = 0
	stack = 0
	i = 0
	while i < len(s):
		c = s[i]
		if c == ')':
			if stack:
				stack -= 1
			else:
				incorrect = 1
				ans += 1
				while incorrect:
					ans += 1
					i += 1
					incorrect += [-1, 1][s[i] == ')']
		else:
			stack += 1
		i += 1
	print(ans)


counter = 0
t = 0
leng = input()
for i in input():
	if i == '(':
		counter += 1
	else:
		counter += -1
	if counter < 0 or (counter == 0 and i == '('):
		t += 1
if counter == 0:
	print(t)
else:
	print(-1)


from os import path
import sys
from math import ceil, floor, gcd, log2
from collections import defaultdict, Counter
maxx = float('inf')
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
	I = lambda : int(sys.stdin.buffer.readline())
	tup = lambda : map(int, sys.stdin.buffer.readline().split())
	lint = lambda : [int(x) for x in sys.stdin.buffer.readline().split()]
	S = lambda : sys.stdin.readline().replace('\n', '').strip()
	stpr = lambda x: sys.stdout.write(f'{x}' + '\n')
	star = lambda x: print(' '.join(map(str, x)))
else:
	I = lambda : int(sys.stdin.buffer.readline())
	tup = lambda : map(int, sys.stdin.buffer.readline().split())
	lint = lambda : [int(x) for x in sys.stdin.buffer.readline().split()]
	S = lambda : sys.stdin.readline().replace('\n', '').strip()
	stpr = lambda x: sys.stdout.write(f'{x}' + '\n')
	star = lambda x: print(' '.join(map(str, x)))
n = I()
s = S()
(a, b) = (s.count('('), s.count(')'))
ans = 0
if a == b:
	(l, r, f, r2) = (0, 0, 1, 0)
	for i in range(len(s)):
		if s[i] == '(':
			l += 1
		else:
			r += 1
		if r > l:
			f = 0
			r2 += 1
		elif r == l:
			if f == 0:
				ans += r2 + 1
				f = 1
				r2 = 0
	print(ans)
else:
	print(-1)


import sys
N = int(input())
word = input()
if N % 2 != 0:
	print(-1)
	sys.exit()
l_cnt = 0
r_cnt = 0
for i in range(N):
	if word[i] == '(':
		l_cnt += 1
	else:
		r_cnt += 1
if l_cnt != r_cnt:
	print(-1)
	sys.exit()
result = 0
checker = 0
l_cnt = 0
r_cnt = 0
for i in range(N):
	if checker == 0:
		checker = word[i]
		if checker == '(':
			l_cnt += 1
		else:
			r_cnt += 1
	else:
		if word[i] == ')':
			r_cnt += 1
		else:
			l_cnt += 1
		if r_cnt == l_cnt:
			if checker == '(':
				pass
			elif word[i] == '(':
				result += l_cnt + r_cnt
			r_cnt = 0
			l_cnt = 0
			checker = 0
print(result)


n = int(input())
s1 = input()
m = 0
s = 0
k = 0
for i in range(len(s1)):
	if s1[i] == '(':
		m += 1
	else:
		m -= 1
	if m < 0:
		k += 1
	elif m == 0:
		k += 1
		s += k
		k = 0
	else:
		k = -1
if m:
	print(-1)
else:
	print(s)


n = int(input())
s = input()
op = 0
ans = 0
bal = False
for i in s:
	if i == '(':
		op += 1
	else:
		op -= 1
	if op < 0:
		ans += 1
		bal = True
	if bal and op == 0:
		ans += 1
		bal = False
if op != 0:
	print(-1)
else:
	print(ans)


n = int(input())
s = input()
k = 0
l = 0
ans = 0
for i in range(len(s)):
	if s[i] == '(':
		k += 1
		f = 1
	else:
		k -= 1
		f = 0
	if k == 0:
		if f:
			ans += i - l + 1
		l = i + 1
if k != 0:
	print(-1)
else:
	print(ans)


n = int(input())
c = input()
a = 0
p = 0
for t in range(n):
	if c[t] == '(':
		a += 1
	else:
		a -= 1
	if a < 0:
		p += 1
	if a == 0 and c[t] == '(':
		p += 1
if a == 0:
	print(p)
else:
	print(-1)


from sys import stdin
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin, tan

def ii():
	return int(stdin.readline())

def fi():
	return float(stdin.readline())

def mi():
	return map(int, stdin.readline().split())

def fmi():
	return map(float, stdin.readline().split())

def li():
	return list(mi())

def lsi():
	x = list(stdin.readline())
	x.pop()
	return x

def si():
	return stdin.readline()
p = s = c = 0
ii()
a = lsi()
for i in a:
	if i == '(':
		p += 1
		if not p:
			s += c * 2
			c = 0
	else:
		p -= 1
		if p < 0:
			c += 1
if p:
	print(-1)
	exit()
print(s)


i = int(input())
s = input()
if s.count(')') != s.count('(') or i % 2 == 1:
	print(-1)
else:
	ans = t = pr = 0
	for x in range(i):
		if s[x] == ')':
			ans -= 1
		else:
			ans += 1
		if t == 0 and ans < 0:
			t = x + 1
		if t != 0 and ans == 0:
			pr += x - t + 2
			t = 0
	print(pr)


n = int(input())
s = input()
count = 0
op = 0
op_count = 0
flag = 0
for (i, c) in enumerate(s):
	if c == ')':
		if count == 0:
			flag = 1
		count -= 1
		op_count += 1
		if count == 0 and flag == 1:
			op += op_count
			op_count = 0
			flag = 0
		if count == 0 and flag == 0:
			op_count = 0
			flag = 0
	else:
		count += 1
		op_count += 1
		if count == 0:
			op += op_count
			op_count = 0
			flag = 0
if count != 0:
	print(-1)
else:
	print(op)


import math
import atexit
import io
import sys
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())

def array_to_string(a):
	s = ''
	for i in a:
		s += str(i)
	return s
n = int(input())
a = [i for i in input()]
close = 0
open = 0
i = 0
if a.count('(') != a.count(')'):
	print(-1)
else:
	v = 0
	k = 0
	while i < len(a):
		if a[i] == ')':
			close += 1
			if open == 0:
				k = 1
		elif a[i] == '(':
			open += 1
		if open == close:
			if k == 1:
				v += 2 * open
				k = 0
			open = 0
			close = 0
		i += 1
	print(v)


a = int(input())
b = input()
(_0, _1, s, r) = (0, 0, 0, -1)
for i in range(a):
	if b[i] == ')':
		_1 += 1
	else:
		_0 += 1
	if _1 > _0 and r == -1:
		r = i
	if _1 == _0 and r != -1:
		s += i - r + 1
		r = -1
		(_1, _0) = (0, 0)
	if _1 == _0:
		(_1, _0) = (0, 0)
if max(_1, _0):
	s = -1
print(s)


n = int(input())
s = input()
t = 0
r = 0
cs = 0
for (i, c) in enumerate(s):
	if c == '(':
		t += 1
	else:
		t -= 1
	if t < 0:
		cs += 1
	elif t == 0 and cs > 0:
		r += cs + 1
		cs = 0
if t != 0:
	print(-1)
else:
	print(r)


a = int(input())
a = list(input())
i = 0
open1 = '('
close = ')'
if a.count(open1) != a.count(close):
	print('-1')
else:
	count = 0
	count1 = 0
	answer = 0
	stack = []
	i = 0
	while i < len(a):
		if len(stack) != 0 and stack[-1] == ')' and (a[i] == '('):
			stack.pop()
			answer += 2
		elif len(stack) != 0 and stack[-1] == '(' and (a[i] == ')'):
			stack.pop()
		else:
			stack.append(a[i])
		i += 1
	print(answer)


size = int(input())
s = input()
s1 = list(s)
a = 0
b = 0
count = 0
for i in s1:
	if i == '(':
		a = a + 1
	else:
		b = b + 1
		if b > a:
			count = count + 1
if a != b:
	print('-1')
else:
	print(count * 2)


n = int(input())
if n % 2:
	print(-1)
	exit()
S = input()
res = 0
current = 0
minus_index = -1
for (i, c) in enumerate(S):
	if c == '(':
		current += 1
	else:
		current -= 1
	if current == 0 and minus_index >= 0:
		res += i - minus_index + 1
		minus_index = -1
	if current < 0 and minus_index == -1:
		minus_index = i
if current != 0:
	print(-1)
else:
	print(res)


n = int(input())
s = input()
o = s.count('(')
c = s.count(')')
if o != c:
	print(-1)
else:
	ans = 0
	c = 0
	o = 0
	l = 0
	for i in s:
		if i == ')':
			c = c + 1
		if i == '(':
			o = o + 1
			if c == o:
				l = l + 1
		if c > o:
			l = l + 1
		if c == o:
			ans = ans + l
			l = 0
	print(ans)


n = int(input())
string = input()
ans = 0
check = True
cnt = 0
temp = 0
for s in string:
	if check:
		if s == '(':
			cnt += 1
		elif cnt == 0:
			check = False
			cnt -= 1
			temp += 1
		else:
			cnt -= 1
	elif s == '(':
		cnt += 1
		temp += 1
		if cnt == 0:
			ans += temp
			check = True
			temp = 0
	else:
		cnt -= 1
		temp += 1
if temp or cnt:
	print(-1)
else:
	print(ans)


n = int(input())
s = input()
if s.count(')') != s.count('('):
	print(-1)
	exit()
ans = 0
p = 0
f = 0
for i in range(n):
	if s[i] == ')':
		p -= 1
	else:
		p += 1
	if p < 0 and (not f):
		st = i - 1
		f = 1
	elif p == 0 and f:
		ans += i - st
		f = 0
print(ans)


n = int(input())
s = input()
c1 = 0
c2 = 0
c = 0
for i in range(n):
	if s[i] == '(':
		c1 += 1
		if c1 == c2:
			c += c1 + c2
			c1 = 0
			c2 = 0
	elif c1 == 0 or c1 < c2:
		c2 += 1
	else:
		c1 -= 1
if c1 != c2:
	print(-1)
else:
	print(c)


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def main():
	n = int(input())
	seq = str(input())
	a = seq.count('(')
	b = seq.count(')')
	if a != b:
		print(-1)
	else:
		ground = 0
		top = seq[0]
		if top == ')':
			ans = 1
			level = -1
			start = -1
		else:
			ans = 0
			level = 1
			start = 1
		for i in range(1, n):
			if level == 0:
				if seq[i] == '(':
					start = 1
				else:
					start = -1
			if start == 1:
				if seq[i] == '(':
					level += 1
				else:
					level -= 1
			else:
				if seq[i] == '(':
					level += 1
				else:
					level -= 1
				ans += 1
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


n = int(input())
brak = [i for i in input()]
open_ = 0
close_ = 0
if brak.count('(') != brak.count(')'):
	print(-1)
else:
	count = 0
	for i in brak:
		if i == '(':
			open_ += 1
		else:
			close_ += 1
			if close_ > open_:
				count += 2
	print(count)


n = int(input())
seq = input()
if seq.count('(') != seq.count(')'):
	print(-1)
else:
	tot = 0
	curr = 0
	for (i, e) in enumerate(seq):
		pre_curr = curr
		if e == '(':
			curr += 1
		else:
			curr -= 1
		if curr < 0 or (pre_curr < 0 and curr == 0):
			tot += 1
	print(tot)


import sys
input = sys.stdin.readline
from math import log2, log, ceil

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return res

def upper_bound(a, x, lo=0):
	hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	while x != link[x]:
		x = link[x]
	return x

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(1000000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

def int_array():
	return list(map(int, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
n = int(input())
string = input().strip()
count = 0
f = 1
sumo = 0
ans = 0
for i in range(n):
	count += 1
	if string[i] == '(':
		sumo += 1
	else:
		sumo -= 1
	if sumo < 0:
		f = 0
	if sumo == 0:
		if f == 0:
			ans += count
			f = 1
		count = 0
if sumo != 0:
	print(-1)
else:
	print(ans)


n = int(input())
l = list(input())
a = '('
b = ')'
(count1, count2) = (0, 0)
c = 0
for i in range(n):
	if l[i] == a:
		count1 += 1
	else:
		count2 += 1
		if count2 > count1:
			c += 1
if count1 != count2:
	print(-1)
else:
	print(2 * c)


_ = input()
s = input()
balance = 0
result = 0
for c in s:
	prev = balance
	if c == '(':
		balance += 1
	else:
		balance -= 1
	if balance < 0:
		result += 1
	elif balance == 0 and prev < 0:
		result += 1
if balance != 0:
	print(-1)
else:
	print(result)


qtd = int(input())
seq = input()
(op, cl) = (list(), list())
cont = 0
for el in seq:
	if el == '(':
		if len(cl) > 0:
			cl.pop()
			cont += 2
		else:
			op.append(el)
	elif len(op) > 0:
		op.pop()
	else:
		cl.append(el)
print(cont if not len(op) and (not len(cl)) else -1)


n = int(input())
arr = list(input())
if arr.count('(') != arr.count(')'):
	print(-1)
else:
	ans = 0
	st = [arr[0]]
	for i in range(1, len(arr)):
		st.append(arr[i])
		if len(st) > 1 and st[-1] == '(' and (st[-2] == ')'):
			ans += 2
			st.pop(len(st) - 1)
			st.pop(len(st) - 2)
		elif len(st) > 1 and st[-1] == ')' and (st[-2] == '('):
			st.pop(len(st) - 1)
			st.pop(len(st) - 2)
	print(ans)


n = int(input())
s = input()
res = 0
op = 0
counter = 1
if s.count('(') != s.count(')'):
	print(-1)
else:
	for i in range(n):
		if s[i] == ')':
			op -= 1
		else:
			op += 1
		if counter > 1 and op == 0:
			res += counter
			counter = 1
		elif op < 0:
			counter += 1
	print(res)


n = int(input())
s = input()
ans = 0
res = 0
for i in s:
	if i == '(':
		ans += 1
	else:
		ans -= 1
	if ans < 0:
		res += 1
	if ans == -1 and i == ')':
		res += 1
if ans != 0:
	print(-1)
else:
	print(res)


def solution(s):
	s = list(s)

	def get_value(b):
		return 1 if b == '(' else -1
	sums = [get_value(s[0])]
	for i in range(1, len(s)):
		sums.append(get_value(s[i]) + sums[i - 1])
	if sums[-1] != 0:
		return -1
	milliseconds = 0
	index = 0
	while index < len(s):
		if sums[index] < 0:
			while index < len(s):
				milliseconds += 1
				s[index] = '(' if s[index] == ')' else ')'
				if sums[index] == 0:
					break
				index += 1
		index += 1
	return milliseconds
input_length = int(input())
input_string = input()
print(solution(input_string))


n = int(input())
s = input()
if n & 1 or s.count(')') != s.count('('):
	print(-1)
else:
	ans = 0
	que = 0
	run = 0
	l = 0
	for x in s:
		que += 1 if x == '(' else -1
		l += 1
		if que == 0:
			ans += l * run
			l = 0
			run = 0
		elif que < 0:
			run = 1
	print(ans)


import sys
input = sys.stdin.readline
from collections import *
n = int(input())
s = input()[:-1]
(l, r) = (0, 0)
ans = 0
for i in range(n):
	if s[i] == '(':
		l += 1
	elif l > 0 and r == 0:
		l -= 1
	else:
		r += 1
	if l == r:
		ans += l + r
		(l, r) = (0, 0)
if l > 0 or r > 0:
	print(-1)
	exit()
print(ans)


import math, collections, sys
n = int(input())
s = input()
ans = 0
z = [0]
for i in s:
	if i == '(':
		z.append(z[-1] + 1)
	else:
		z.append(z[-1] - 1)
flag = 0
neg = 0
for i in range(n + 1):
	if flag:
		if z[i] == 0:
			ans += i - neg + 1
			flag = 0
	elif z[i] < 0:
		neg = i
		flag = 1
if z[-1] != 0:
	print(-1)
else:
	print(ans)


n = int(input())
s = input()
c = 0
state = 0
prev = 0
for i in s:
	if i == '(':
		state += 1
	else:
		state -= 1
	if state < 0:
		c += 1
	elif state == 0 and prev < 0:
		c += 1
	prev = state
if state != 0:
	print(-1)
else:
	print(c)


ll = lambda : map(int, input().split())
t = lambda : int(input())
ss = lambda : input()
lx = lambda x: map(int, input().split(x))

def f():
	n = t()
	s = ss()
	a = 0
	b = 0
	c = 0
	if n % 2 == 1:
		print(-1)
		return
	for i in s:
		if i == '(':
			a += 1
		elif i == ')':
			a -= 1
			if a < 0:
				c += 2
	print(c if a == 0 else -1)
f()


n = int(input())
seq = list(input())
if n % 2 == 1:
	print(-1)
else:
	s = 0
	res = 0
	for c in seq:
		if c == '(':
			s += 1
		elif c == ')':
			s -= 1
		if s < 0:
			res += 1
		elif s == 0 and c == '(':
			res += 1
	if s != 0:
		print(-1)
	else:
		print(res)


x = input()
string = input()
open_bracket = 0
close_bracket = 0
operations = 0
for c in string:
	if c == '(':
		open_bracket += 1
	else:
		close_bracket += 1
		if close_bracket > open_bracket:
			operations += 1
if open_bracket != close_bracket:
	print(-1)
else:
	print(operations * 2)


n = int(input())
s = input()
l = 0
r = 0
cnt = 0
ans = 0
for i in s:
	if i == ')':
		cnt -= 1
		l += 1
		if cnt < 0:
			ans += 1
	else:
		cnt += 1
		r += 1
		if cnt <= 0:
			ans += 1
if l == r:
	print(ans)
else:
	print('-1')


n = int(input())
s = str(input())
if n % 2 == 1:
	print(-1)
else:
	num_of_op = num_of_clos = 0
	for i in range(n):
		if s[i] == '(':
			num_of_op += 1
		else:
			num_of_clos += 1
	if num_of_op != num_of_clos:
		print(-1)
	else:
		fl = True
		now = balance = 0
		ans = 0
		for i in range(n):
			if s[i] == '(':
				balance += 1
			else:
				balance -= 1
			now += 1
			if balance == 0:
				if fl == False:
					ans += now
				now = 0
				fl = True
			elif balance < 0:
				fl = False
		print(ans)


n = int(input())
s = input()
if s.count('(') != s.count(')'):
	print(-1)
else:
	ans = 0
	(pre, a, b) = (-1, 0, 0)
	for i in range(len(s)):
		if s[i] == '(':
			a += 1
			if a == b:
				ans += i - pre
				pre = i
		else:
			b += 1
			if a == b:
				pre = i
	print(ans)


import sys, math
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())
t = 1
for tt in range(t):
	n = inp()
	a = insr()
	q = a.count('(')
	w = a.count(')')
	qq = 0
	if q == w:
		c = 0
		cc = 0
		for i in range(len(a)):
			if c == 0:
				if a[i] == '(':
					qw = 1
				else:
					qw = 0
			if a[i] == '(':
				c = c + 1
			else:
				c = c - 1
			cc = cc + 1
			if c == 0:
				if qw == 0:
					qq = qq + cc
				cc = 0
	else:
		qq = -1
	print(qq)


def solver(arr):
	t = 0
	cnt = 0
	for i in arr:
		if i == '(':
			if cnt < 0:
				t += 2
			cnt += 1
		else:
			cnt -= 1
	if cnt == 0:
		return t
	else:
		return -1
i = int(input())
arr = input()
print(solver(arr))


n = int(input())
string = list(input())
nanosecs = 0
w = [0] * n
if string.count('(') == string.count(')'):
	for i in range(len(string)):
		if i == 0:
			if string[i] == '(':
				w[i] = 1
			else:
				w[i] = -1
				nanosecs += 1
		elif string[i] == '(':
			w[i] = w[i - 1] + 1
			if w[i - 1] < 0:
				nanosecs += 1
		else:
			w[i] = w[i - 1] - 1
			if w[i] < 0:
				nanosecs += 1
else:
	nanosecs = -1
print(nanosecs)


n = int(input())
seq = input()
counter = 0
bad_counter = 0
prev_counter = 0
for s in seq:
	if s == '(':
		counter += 1
	else:
		counter -= 1
	if counter < 0 or (counter == 0 and prev_counter == -1):
		bad_counter += 1
	prev_counter = counter
if counter != 0:
	print(-1)
else:
	print(bad_counter)


n = int(input())
s = input()
b = 0
last = -1
ans = 0
for x in range(n):
	if s[x] == '(':
		b += 1
	else:
		b -= 1
	if b < 0 and last == -1:
		last = x
	if b == 0 and last != -1:
		ans += x - last + 1
		last = -1
if b != 0:
	ans = -1
print(ans)


def fn():
	diff = 0
	ans = 0
	f = 'p'
	n = int(input())
	s = input()
	if len(s) % 2 == 1:
		return -1
	for i in range(n):
		if s[i] == '(':
			diff += 1
		elif s[i] == ')':
			diff -= 1
		if diff >= 0:
			f = 'p'
			continue
		elif diff < 0:
			ans += 1
			if f == 'p':
				f = 'n'
				ans += 1
	if diff == 0:
		return ans
	else:
		return -1
print(fn())


n = int(input())
s = input()
(c_0, c_1, ans) = (0, 0, 0)
isPossible = False
for i in s:
	if i == '(':
		c_0 += 1
	else:
		c_1 += 1
if c_0 != c_1:
	print(-1)
	exit(0)
(c_0, c_1) = (0, 0)
l = -1
for i in range(len(s)):
	if s[i] == '(':
		c_0 += 1
	else:
		c_1 += 1
	if c_0 == c_1:
		if s[i] == '(':
			ans += i - l
		(l, c_0, c_1) = (i, 0, 0)
print(ans)


def f(L):
	ret = 0
	(o, e) = (0, 0)
	iscorrect = True
	stk = 0
	for i in range(len(L)):
		if L[i] == '(':
			stk += 1
			o += 1
		else:
			if stk == 0:
				iscorrect = False
			stk -= 1
			e += 1
		if o == e:
			if iscorrect and stk == 0:
				o = e = 0
				continue
			iscorrect = True
			stk = 0
			ret += o + e
			o = e = 0
	if not o == e == 0:
		return -1
	return ret
n = int(input())
print(f(input()))


import math
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
n = int(input())
s = input()
o = 0
c = 0
cnt = 0
for i in s:
	if i == '(':
		o += 1
	elif i == ')':
		c += 1
		if c > o:
			cnt += 2
if o != c:
	print('-1')
else:
	print(cnt)


N = int(input())
S = input()
if N % 2 != 0:
	print(-1)
else:
	a = 0
	b = 0
	for i in S:
		if i == '(':
			b += 1
			if b <= 0:
				a += 1
		else:
			b -= 1
			if b < 0:
				a += 1
	print(-1) if b != 0 else print(a)


n = int(input())
s = input()
cnt = ans = 0
for i in s:
	if i == '(':
		cnt -= 1
		if cnt >= 0:
			ans += 1
	elif i == ')':
		cnt += 1
		if cnt > 0:
			ans += 1
if cnt == 0:
	print(ans)
else:
	print(-1)


n = int(input())
l = ''.join([x for x in input()])
if n % 2 == 1:
	print(-1)
else:
	tot = 0
	res = 0
	for i in range(n):
		if l[i] == '(':
			tot += 1
			if tot <= 0:
				res += 1
		else:
			if tot <= 0:
				res += 1
			tot -= 1
	if tot != 0:
		print(-1)
	else:
		print(res)


n = int(input())
string = input()
if string.count('(') != string.count(')'):
	print(-1)
else:
	stack = ['#']
	res = 0
	res = 0
	f = 0
	for s in string:
		if s == '(' and f == 0:
			stack.append(s)
		elif s == '(':
			res += 1
			f -= 1
		elif stack[-1] == '(':
			stack.pop()
		else:
			res += 1
			f += 1
	print(res)


from sys import stdin, stdout
LI = lambda : list(map(int, input().split()))
MAP = lambda : map(int, input().split())
IN = lambda : int(input())
S = lambda : input()
import math
from collections import Counter

def solve():
	n = IN()
	s = S()
	a = 0
	b = 0
	for i in s:
		if i == '(':
			b += 1
		else:
			b -= 1
			if b < 0:
				a += 2
	if b != 0:
		print(-1)
	else:
		print(a)
for i in range(1):
	solve()


n = int(input())
s = input()
li = []
for i in s:
	if i == '(':
		li.append(1)
	else:
		li.append(-1)
if sum(li) != 0:
	print(-1)
else:
	startset = 0
	ans = 0
	l = []
	for i in range(n):
		if li[i] == 1:
			if l == []:
				if startset == 1:
					end = i
					ans += end - start
					startset = 0
				l.append(1)
			elif l[-1] == -1:
				l.pop(-1)
			else:
				l.append(1)
		elif li[i] == -1 and l == []:
			if startset == 0:
				startset = 1
				start = i
				end = i
			else:
				end = i
			l.append(-1)
		elif l[-1] == 1:
			l.pop(-1)
		else:
			end = i
			l.append(-1)
	if startset == 1:
		ans += n - start
	print(ans)


n = int(input())
s = input()
x = 0
y = 0
p = 0
for i in s:
	if i == '(':
		x += 1
		if y != 0:
			x -= 1
			y -= 1
			p += 2
	else:
		y += 1
		if x != 0:
			x -= 1
			y -= 1
if x == 0 and y == 0:
	print(p)
else:
	print(-1)


n = int(input())
l = list(input())
if n % 2 != 0:
	print(-1)
else:
	count = 0
	brack = 0
	for i in range(n):
		if l[i] == '(':
			brack += 1
		else:
			brack -= 1
			if brack < 0:
				count += 2
	if brack != 0:
		print(-1)
	else:
		print(count)


import sys
read = lambda : list(map(int, sys.stdin.readline().strip().split()))
n = int(input())
s = input()
o = 0
c = 0
for i in range(n):
	if s[i] == '(':
		o += 1
	else:
		c += 1
if o != c:
	print('-1')
else:
	ans = 0
	o = 0
	c = 0
	for i in range(n):
		if o == c + 1 and s[i] == ')':
			o = 0
			c = 0
		elif c == o + 1 and s[i] == '(':
			ans += 2 * c
			c = 0
			o = 0
		elif s[i] == '(':
			o += 1
		else:
			c += 1
	print(ans)


import sys
input = sys.stdin.readline
from collections import defaultdict

def main():
	n = int(input())
	s = input()
	cnt = defaultdict(int)
	for i in range(n):
		cnt[s[i]] += 1
	if cnt['('] != cnt[')']:
		print(-1)
		exit()
	ans = 0
	bal = 0
	bad = False
	last = 0
	for i in range(n):
		if s[i] == '(':
			bal += 1
		else:
			bal -= 1
		if bal == 0:
			if bad:
				ans += i - last + 1
				last = i + 1
				bad = False
			else:
				last = i + 1
				bad = False
		elif bal < 0:
			bad = True
	print(min(n, ans))
main()


n = int(input())
l = input()
o = l.count('(')
c = l.count(')')
t = 0
if o == c:
	a = 0
	s = 0
	for i in range(n):
		if l[i] == '(':
			if a == -1:
				t += i - s + 1
				s = i + 1
			a += 1
		else:
			a -= 1
		if a == 0:
			s = i + 1
	print(t)
else:
	print(-1)


n = int(input())
s = str(input())
(res, bf) = (0, 0)
if n % 2 != 0:
	print('-1')
else:
	for i in range(n):
		if s[i] == ')':
			bf = bf - 1
		else:
			bf = bf + 1
			if bf == 0:
				res = res + 1
		if bf < 0:
			res = res + 1
	if bf == 0:
		print(res)
	else:
		print('-1')


n = int(input())
s = input()
s1 = s.count('(')
s2 = s.count(')')
ans = 0
if n & 1 != 0 or s1 != s2:
	print(-1)
else:
	summ = 0
	out = []
	for i in range(n):
		if s[i] == '(':
			summ += 1
			out.append(i)
		else:
			if len(out) > 0 and s[out[-1]] == '(':
				out.pop()
			else:
				out.append(i)
			summ -= 1
		if summ == 0 and out:
			ans += out[-1] - out[0] + 1
			out = []
	if out:
		ans += out[-1] - out[0] + 1
	print(ans)


import sys
input = sys.stdin.readline
n = int(input())
s = input()
l = list()
open = list()
close = list()
for i in range(n):
	if s[i] == '(':
		open.append(i)
	else:
		close.append(i)
if len(open) != len(close):
	print(-1)
else:
	ans = 0
	for i in range(len(open)):
		if open[i] > close[i]:
			ans += 2
	print(ans)


n = int(input())
l = input()
if n % 2 == 1 or l.count('(') != n // 2:
	print(-1)
	exit(0)
s = 0
t = 0
for i in range(n):
	if l[i] == '(':
		if t == -1:
			s += 1
		t += 1
	else:
		t -= 1
	if t < 0:
		s += 1
print(s)


n = int(input())
s = input()
(op, cl) = (0, 0)
ind = 0
flag = 0
for i in range(len(s)):
	if op < 0:
		flag = 1
	else:
		flag = 0
	if s[i] == '(':
		op += 1
	else:
		op -= 1
	if op == -1 and s[i] == ')':
		ind = i
	if flag and op == 0:
		cl += i - ind + 1
if op != 0:
	print(-1)
else:
	print(cl)


import sys
import math
import itertools
import functools
import collections
import operator
import fileinput
import copy
ORDA = 97

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return list(map(int, input().split()))

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def revn(n):
	return str(n)[::-1]

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=1):
	r = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				r.append(i)
			else:
				r.extend([i, n // i])
	return r

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def prime(n):
	if n == 2:
		return True
	if n % 2 == 0 or n <= 1:
		return False
	sqr = int(math.sqrt(n)) + 1
	for d in range(3, sqr, 2):
		if n % d == 0:
			return False
	return True

def convn(number, base):
	newnumber = 0
	while number > 0:
		newnumber += number % base
		number //= base
	return newnumber

def cdiv(n, k):
	return n // k + (n % k != 0)
n = ii()
s = input()
if n & 1:
	print(-1)
else:
	ans = 0
	bal = 0
	for i in range(n):
		if s[i] == ')':
			bal -= 1
			if bal < 0:
				ans += 1
		else:
			bal += 1
			if bal <= 0:
				ans += 1
	if bal != 0:
		print(-1)
	else:
		print(ans)


n = int(input())
s = input()
if n % 2 == 1 or s.count(')') != s.count('('):
	print('-1')
else:
	sy = 0
	k = 0
	w = 0
	for i in range(n):
		if s[i] == '(':
			sy += 1
		else:
			sy -= 1
		if sy == 0:
			w = 0
		if sy < 0:
			k += 1
			if w == 0:
				k += 1
				w = 1
	print(k)


n = int(input())
S = input()
ans = 0
count = 0
op = float('inf')
for (i, x) in enumerate(S):
	if x == '(':
		count += 1
	elif x == ')':
		count -= 1
		if count == -1:
			op = i
	if count == 0:
		if op < i:
			ans += i - op + 1
			op = float('inf')
if count != 0:
	print(-1)
else:
	print(ans)


import io
import os
from collections import deque, defaultdict, Counter

def solve(N, S):
	balance = 0
	cost = 0
	last = None
	for (i, x) in enumerate(S):
		if x == '(':
			balance += 1
		if x == ')':
			balance -= 1
		if balance == -1 and last is None:
			last = i
		elif balance == 0 and last is not None:
			cost += i - last + 1
			last = None
	if balance != 0:
		return -1
	return cost
(N,) = list(map(int, input().split()))
S = input().rstrip()
ans = solve(N, S)
print(ans)


import sys
input = sys.stdin.readline
n = int(input())
s = list(input())
if n % 2 == 1:
	print(-1)
	exit()
if s.count('(') != n // 2:
	print(-1)
	exit()
ma = 0
c = 0
res = 0
for i in range(n):
	if c <= 0 and s[i] == ')':
		res += 1
	elif c < 0 and s[i] == '(':
		res += 1
	if s[i] == '(':
		c += 1
	else:
		c -= 1
print(res)


n = int(input())
s = input().strip()
c = 0
v = 0
o = 0
cl = 0
for j in range(n):
	if s[j] == '(':
		o = o + 1
		if cl > 0:
			v = v + 1
	else:
		cl = cl + 1
		if o == 0:
			v = v + 1
		if o > 0:
			cl = cl - 1
			o = o - 1
			if cl > 0:
				v = v + 1
	if o == cl:
		c = c + v
		v = 0
		o = 0
		cl = 0
if o != cl:
	c = -1
print(c)


n = int(input())
list_ = list(input())

def transform_string(list_):
	final_list = list()
	if list_[-1] == ')':
		final_list.append(1)
	else:
		final_list.append(-1)
	for i in range(2, n + 1):
		final_list.append(final_list[i - 2] + (list_[-i] == ')') * 1 + (list_[-i] == '(') * -1)
	return final_list
cum_sum = transform_string(list_)
if cum_sum[-1] != 0:
	print(-1)
elif min(cum_sum) >= 0:
	print(0)
else:
	final_sum = 0
	s = 0
	for i in range(n):
		if cum_sum[i] < 0:
			s += 1
		else:
			if i > 0 and cum_sum[i] == 0 and (cum_sum[i - 1] < 0):
				s += 1
			final_sum += s
			s = 0
	print(final_sum)


import sys
input = sys.stdin.readline
n = int(input())
s = input().rstrip()
prev_lv = 1
level = 0
start = 0
ans = 0
for (i, ch) in enumerate(s):
	if ch == ')':
		level -= 1
	else:
		level += 1
	if prev_lv == 1 and level == 0:
		start = i + 1
	if prev_lv == -1 and level == 0:
		ans += i + 1 - start
		start = i + 1
	prev_lv = level
if level != 0:
	print(-1)
else:
	print(ans)


n = int(input())
s = input()
if n & 1:
	print(-1)
else:
	sum = 0
	for ch in s:
		if ch == '(':
			sum += 1
		else:
			sum -= 1
	if sum != 0:
		print(-1)
	else:
		sum = 0
		ans = 0
		i = 0
		end = 0
		while i != n:
			if s[i] == '(':
				sum += 1
			else:
				sum -= 1
			if sum < 0:
				start = i
				while sum != 0:
					end = i + 1
					i += 1
					if s[i] == '(':
						sum += 1
					else:
						sum -= 1
				ans += end - start + 1
			i += 1
		print(ans)


num_of_par = int(input())
data = list(input())
counter = 0
result = 0
for item in data:
	if item == '(':
		if counter == -1:
			result += 1
		counter += 1
	else:
		counter -= 1
	if counter < 0:
		result += 1
if counter != 0:
	print('-1')
else:
	print(result)


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().strip().split(' '))

def msi():
	return map(str, input().strip().split(' '))

def li():
	return list(mi())

def dmain():
	sys.setrecursionlimit(100000000)
	threading.stack_size(40960000)
	thread = threading.Thread(target=main)
	thread.start()
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def getKey(item):
	return item[0]

def sort2(l):
	return sorted(l, key=getKey)

def d2(n, m, num):
	return [[num for x in range(m)] for y in range(n)]

def isPowerOfTwo(x):
	return x and (not x & x - 1)

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def ntl(n):
	return [int(i) for i in str(n)]

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(n - r))

def powerMod(x, y, p):
	res = 1
	x %= p
	while y > 0:
		if y & 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def main():
	n = ii()
	s = si()
	x = s.count('(')
	y = s.count(')')
	if x != y:
		print(-1)
		exit()
	time = 0
	c = 0
	f = 0
	start = 0
	for i in range(n):
		if s[i] == '(':
			c += 1
		else:
			c -= 1
		if f == 1 and c == 0:
			time += i - start + 1
			start = i
			f = 0
		if c < 0 and f == 0:
			start = i
			f = 1
	print(time)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def search(arr, n, x):
	f = 0
	for i in arr:
		if i == x:
			f += 1
	return f
n = int(input())
b = input()
left = search(b, n, '(')
right = search(b, n, ')')
if left == right:
	f = 0
	c = 0
	for x in b:
		if x == ')':
			f -= 1
		if f < 0:
			c += 1
		if x == '(':
			f += 1
	print(c)
else:
	print(-1)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
mod = int(pow(10, 9) + 7)
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def L():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
try:
	sys.stdin = open('input.txt', 'r')
except:
	pass
n = L()[0]
s = input()
x = s.count('(')
y = s.count(')')
if x != y:
	print(-1)
	exit()
count = 0
t = 0
undone = 0
for i in range(n):
	if s[i] == '(':
		count += 1
	else:
		count -= 1
	if count < 0:
		t -= count
		count = 0
		undone += 1
	if s[i] == '(' and undone:
		t += 1
		count -= 1
		undone -= 1
print(t)


from collections import Counter
from collections import defaultdict
import math
n = int(input())
s = list(input())
l = list()
ind = -1
c = 0
ans = 0
for i in range(0, n):
	if s[i] == ')':
		c = c - 1
		if c == -1:
			ind = i
	else:
		if c + 1 == 0:
			ans = ans + i - ind + 1
		c = c + 1
if c == 0:
	print(ans)
else:
	print(-1)


n = int(input())
seq = input()
suma = 0
sumb = 0
for i in seq:
	if i == '(':
		suma = suma + 1
	else:
		sumb = sumb + 1
if suma != sumb:
	print('-1')
else:
	sm = 0
	ans = 0
	i = 0
	while i < len(seq):
		sm = sm + 1 if seq[i] == '(' else sm - 1
		if sm < 0:
			j = i
			i = i + 1
			while i < len(seq) and sm < 0:
				sm = sm + 1 if seq[i] == '(' else sm - 1
				i = i + 1
			ans = ans + i - j
		else:
			i = i + 1
	print(ans)


n = int(input())
s = input()
cnt = []
a = 0
for i in range(n):
	if s[i] == '(':
		a += 1
	else:
		a -= 1
	cnt.append(a)
if a != 0:
	print('-1')
else:
	cont = 0
	if cnt[0] < 0:
		cont += 1
	for i in range(1, len(cnt)):
		if cnt[i] < 0:
			cont += 1
		elif cnt[i] == 0 and cnt[i - 1] < 0:
			cont += 1
	print(cont)


(n, s) = (int(input()), input())
(cc, cur, ix) = (0, 0, -1)
for i in range(n):
	prev = cur
	cur += 1 if s[i] == '(' else -1
	if cur == 0:
		if prev < 0:
			cc += i - ix
		ix = i
print(-1 if cur else cc)


n = int(input())
s = input()
c = 0
prev = 0
total = 0
for x in s:
	if x == '(':
		c += 1
	else:
		c -= 1
	if c < 0 or (c == 0 and prev < 0):
		total += 1
	prev = c
if c != 0:
	print(-1)
else:
	print(total)


n = int(input())
a = input()
na = 0
nb = 0
ac = 0
vc = 0
flag = 0
for i in range(n):
	if a[i] == '(':
		ac = ac - 1
		na = na + 1
	else:
		ac = ac + 1
		nb = nb + 1
	if ac > 0:
		flag = 1
		vc = vc + 1
	else:
		if flag == 1:
			vc = vc + 1
		flag = 0
if na != nb:
	print(-1)
else:
	print(vc)


import sys
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
length = inp()
seq = insr()
count = 0
nanos = 0
i = 0
while i < length:
	if seq[i] == '(':
		count += 1
		if count <= 0:
			nanos += 1
	else:
		count -= 1
		if count < 0:
			nanos += 1
	i += 1
if count != 0:
	print(-1)
else:
	print(nanos)


n = int(input())
st = 0
co = 0
ind = -1
tot = 0
tot2 = 0
s = list(input())
for i in range(n):
	if s[i] == '(':
		tot2 += 1
	if st == 0:
		if s[i] == '(':
			co += 1
		else:
			co -= 1
		if co < 0:
			st = 1
			ind = i
	else:
		if s[i] == '(':
			co += 1
		else:
			co -= 1
		if co == 0:
			tot += i - ind + 1
			st = 0
if tot2 == n - tot2:
	print(tot)
else:
	print(-1)


(__, s) = (input(), input())
(a, n) = (0, 0)
pt = {'(': 1, ')': -1}
for c in s:
	da = pt.get(c, 0)
	if a < 0 or a + da < 0:
		n += 1
	a += da
if a != 0:
	print(-1)
else:
	print(n)


def f():
	n = int(input())
	if n % 2:
		print(-1)
		return
	d = {'(': 0, ')': 1}
	S = [d[char] for char in input()]
	c = 0
	for s in S:
		c += s
	if 2 * c != n:
		print(-1)
		return
	ans = 0
	flag = 0
	c = 0
	for (i, s) in enumerate(S):
		c += s
		if not flag:
			if 2 * c > i + 1:
				left = i
				flag = 1
		if flag:
			if 2 * c <= i + 1:
				right = i
				ans += right - left + 1
				flag = 0
	print(ans)
f()


from sys import stdin
a = int(stdin.readline())
c = stdin.readline()
count = 0
count2 = 0
record = 0
for b in range(0, a):
	if c[b] == '(':
		if count < 0:
			count2 += 1
		count += 1
		if count == 0:
			record += count2
			count2 = 0
	else:
		count -= 1
		if count < 0:
			count2 += 1
if count != 0:
	print(-1)
else:
	print(record)


l = int(input())
s = input()
close = 0
open = 0
x = 0
change = False
for i in s:
	if i == '(':
		open += 1
	else:
		close += 1
	if close > open:
		change = True
		x += 1
	if open == close and change:
		x += 1
		change = False
if open != close:
	print(-1)
else:
	print(x)


def examA():
	t = I()
	ans = []
	for _ in range(t):
		N = I()
		A = LI()
		flag = False
		for (i, a) in enumerate(A):
			if a % 2 == 0:
				flag = True
				ans.append((1, i + 1))
				break
		if flag:
			continue
		if N == 1:
			ans.append(-1)
			continue
		ans.append(2)
	for v in ans:
		if v == 2:
			print(2)
			print('1 2')
		elif v == -1:
			print(-1)
		else:
			print(v[0])
			print(v[1])
	return

def examB():

	def make_divisors(n):
		divisors = []
		for i in range(1, int(n ** 0.5) + 1):
			if n % i == 0:
				divisors.append(i)
				if i != n // i:
					divisors.append(n // i)
		return divisors
	(N, M, K) = LI()
	a = LI()
	b = LI()
	A = defaultdict(int)
	B = defaultdict(int)
	cur = 0
	for i in range(N):
		if a[i] == 1:
			cur += 1
		elif cur >= 1:
			A[cur] += 1
			cur = 0
	if cur > 0:
		A[cur] += 1
	cur = 0
	for i in range(M):
		if b[i] == 1:
			cur += 1
		elif cur >= 1:
			B[cur] += 1
			cur = 0
	if cur > 0:
		B[cur] += 1
	SA = [0] * (N + 2)
	SB = [0] * (M + 2)
	for i in range(1, N + 1)[::-1]:
		SA[i] = SA[i + 1] + A[i]
	for i in range(1, M + 1)[::-1]:
		SB[i] = SB[i + 1] + B[i]
	SA2 = [0] * (N + 2)
	SB2 = [0] * (M + 2)
	for i in range(1, N + 1)[::-1]:
		SA2[i] = SA2[i + 1] + SA[i + 1] + A[i]
	for i in range(1, M + 1)[::-1]:
		SB2[i] = SB2[i + 1] + SB[i + 1] + B[i]
	S = make_divisors(K)
	if len(S) % 2 == 1:
		S.append(S[-1])
	loop = len(S) // 2
	ans = 0
	for i in range(loop):
		x = S[i * 2]
		y = S[i * 2 + 1]
		if x <= N and y <= M:
			ans += SA2[x] * SB2[y]
		if x == y:
			continue
		x = S[i * 2 + 1]
		y = S[i * 2]
		if x <= N and y <= M:
			ans += SA2[x] * SB2[y]
	print(ans)
	return

def examC():
	N = I()
	S = SI()
	out = -1
	cur = 0
	ans = 0
	for (i, s) in enumerate(S):
		if out < 0:
			if s == '(':
				cur += 1
			else:
				cur -= 1
			if cur < 0:
				out = i
		else:
			if s == '(':
				cur += 1
			else:
				cur -= 1
			if cur == 0:
				ans += i - out + 1
				out = -1
	if cur != 0:
		print(-1)
		return
	print(ans)
	return

def examD():
	ans = 0
	print(ans)
	return

def examE():
	ans = 0
	print(ans)
	return

def examF():
	ans = 0
	print(ans)
	return
import sys, copy, bisect, itertools, heapq, math, random
from heapq import heappop, heappush, heapify
from collections import Counter, defaultdict, deque

def I():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LSI():
	return list(map(str, sys.stdin.readline().split()))

def LS():
	return sys.stdin.readline().split()

def SI():
	return sys.stdin.readline().strip()
global mod, mod2, inf, alphabet, _ep
mod = 10 ** 9 + 7
mod2 = 998244353
inf = 10 ** 18
_ep = 10 ** (-12)
alphabet = [chr(ord('a') + i) for i in range(26)]
examC()


n = int(input())
s = input()
P = []
o = 0
c = 0
pre = 0
for i in s:
	if i == '(':
		o += 1
		pre += 1
	else:
		c += 1
		pre -= 1
	P.append(pre)
if c == o:
	ans = 0
	count = 0
	for i in range(n):
		if P[i] < 0:
			count += 1
		elif P[i] == 0 and count > 0:
			ans += count + 1
			count = 0
	print(ans)
else:
	print('-1')


n = int(input())
s = input()
if s.count('(') != s.count(')'):
	print(-1)
else:
	a = 0
	c = 0
	for item in s:
		if item == ')':
			a -= 1
		else:
			a += 1
		if a < 0 or (a == 0 and item == '('):
			c += 1
	print(c)


n = int(input())
a = input()
if a.count('(') != a.count(')'):
	print('-1')
else:
	c = 0
	d = 0
	for i in a:
		if i == '(':
			c += 1
		else:
			c -= 1
			if c < 0:
				d += 2
	print(d)


input()
s = list(input())
a = 0
cnt = 0
if s.count(')') != s.count('('):
	print(-1)
else:
	for item in s:
		if a < 0 or (a == 0 and item == ')'):
			cnt += 1
		if item == '(':
			a += 1
		else:
			a -= 1
	print(cnt)


import sys
input = sys.stdin.readline

def main():
	t = 1
	while t:
		t -= 1
		n = int(input())
		s = input()
		bal = 0
		ned = 0
		ls = 0
		ans = 0
		for i in range(n):
			if s[i] == '(':
				bal += 1
			else:
				bal -= 1
			if bal == 0:
				if ned:
					ned = 0
					ans += i - ls + 1
			if bal < 0:
				if not ned:
					ned = 1
					ls = i
		print(ans if not bal else -1)
main()


t = int(input())
s = input()
c = 0
r = 0
for i in s:
	if i == '(':
		c += 1
	else:
		c += -1
		if c < 0:
			r += 2
if c != 0:
	print(-1)
else:
	print(r)


import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict

def solution(n, brac):
	if n & 1 == 1:
		print(-1)
		return
	(sums, res) = (0, 0)
	for c in brac:
		if c == '(':
			sums += 1
		if c == ')':
			sums -= 1
		if sums < 0:
			res += 1
		if sums == -1 and c == ')':
			res += 1
	if sums:
		print(-1)
		return
	print(res)

def main():
	n = int(input())
	brac = input()
	solution(n, list(brac))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')

def read_array(arr):
	return [int(x) for x in arr.split()]
main()


n = int(input())
s = input()
cnt = 0
flag = 0
ans = 0
pre = 0
i = 1
for c in s:
	if c == '(':
		cnt += 1
	else:
		cnt -= 1
	if cnt == 0 and c == '(':
		ans += i - pre + 1
	if cnt == -1 and c == ')':
		pre = i
	i += 1
if cnt == 0:
	print(ans)
else:
	print(-1)


n = int(input())
word = input()
if len(word) % 2 != 0:
	print(-1)
else:
	(cl, op) = ([], [])
	for i in range(len(word)):
		if word[i] == ')':
			cl.append(i)
		else:
			op.append(i)
	if len(op) != len(cl):
		print(-1)
	else:
		ans = 0
		l = 0
		i = 0
		f = 0
		while i < len(op):
			if op[i] > cl[i]:
				l += 2
			elif l != 0:
				ans += l
				f = 0
				l = 0
			i += 1
		if l != 0:
			ans += l
		print(ans)


n = int(input())
s = input()
cn = 0
ans = 0
a = []
b = []
for i in s:
	if i == ')':
		if len(a) > 0:
			a.pop()
		else:
			b.append(i)
			cn += 1
	elif len(b) > 0:
		b.pop()
		cn += 1
	else:
		a.append(i)
	if len(b) == 0:
		ans += cn
		cn = 0
if len(b) > 0 or len(a) > 0:
	print(-1)
else:
	print(ans)


n = int(input())
s = input()
if s.count('(') != s.count(')'):
	print(-1)
else:
	bal = 0
	answer = 0
	for i in s:
		if i == '(':
			bal += 1
		else:
			bal -= 1
			if bal < 0:
				answer += 2
	print(answer)


n = int(input())
a = input()
b = 0
c = 0
d = [0]
e = 0
for i in range(n):
	if a[i] == '(':
		b = b + 1
		e = e + 1
		d.append(e)
	else:
		c = c + 1
		e = e - 1
		d.append(e)
if b != c:
	print(-1)
else:
	b = []
	for i in range(len(d)):
		if d[i] == 0:
			b.append(i)
	s = 0
	for i in range(len(b) - 1):
		c = 0
		for j in d[b[i] + 1:b[i + 1]]:
			if j > 0:
				c = c + 1
		if c == b[i + 1] - b[i] - 1:
			s = s + c + 1
	print(n - s)


n = int(input())
br = str(input())
stack = [br[0]]
counter = 1
output = 0
hold = 0
if br[0] == '(':
	hold = -1
else:
	hold = 1
for i in range(1, len(br)):
	counter = counter + 1
	if br[i] == '(':
		stack.append(br[i])
		hold = hold - 1
	else:
		try:
			if stack[-1] == '(':
				stack.pop(-1)
				hold = hold + 1
			else:
				stack.append(br[i])
				hold = hold + 1
		except:
			stack.append(br[i])
			hold = hold + 1
	if len(stack) != 0 and hold == 0:
		output = output + counter
		counter = 0
		stack = []
	if len(stack) == 0:
		counter = 0
if stack != []:
	print(-1)
else:
	print(output)


n = int(input())
s = input().strip()
negcount = 0
poscount = 0
flag = False
ans = 0
for i in range(len(s)):
	if s[i] == ')':
		if poscount == 0:
			flag = True
		negcount += 1
	else:
		poscount += 1
	if negcount == poscount:
		if flag:
			ans += 2 * negcount
			negcount = 0
			poscount = 0
			flag = False
		else:
			negcount = 0
			poscount = 0
			flag = False
if negcount != poscount:
	print(-1)
	exit()
print(ans)


from sys import stdin, stdout

def main():
	n = int(input())
	s = input()
	(nc, no) = (0, 0)
	c = 0
	ans = 0
	for i in range(n):
		if s[i] == ')':
			nc += 1
		if s[i] == '(':
			no += 1
		if nc > no and c == 0:
			c = 1
			index = i
		if nc == no and c == 1:
			ans += i - index + 1
			c = 0
	if no != nc:
		print(-1)
	else:
		print(ans)
main()


n = int(input())
s = input()
ans = 0
res = 0
flag = 0
temp = 0
for i in s:
	if i == '(':
		ans += 1
	else:
		ans -= 1
	if ans < 0:
		flag = 1
	elif ans == 0:
		if flag == 1:
			res += temp + 1
		temp = -1
		flag = 0
	temp += 1
if ans != 0:
	print(-1)
else:
	print(res)


n = int(input())
a = input()
l = []
k = []
c = cnt = 0
for i in range(n):
	if a[i] == '(':
		c = c + 1
	else:
		c = c - 1
	if c < 0:
		cnt += 1
	if c == 0 and i > 0 and (a[i] == '('):
		cnt += 1
if c == 0:
	print(cnt)
else:
	print('-1')


import sys
input = sys.stdin.readline
n = int(input())
S = input().strip()
A = 0
B = 0
for s in S:
	if s == '(':
		A += 1
	else:
		B += 1
if A != B:
	print(-1)
	sys.exit()
NOW = [0]
for i in range(n):
	if S[i] == ')':
		NOW.append(NOW[-1] - 1)
	else:
		NOW.append(NOW[-1] + 1)
score = 0
ANS = 0
for i in range(n + 1):
	if NOW[i] < 0:
		score += 1
	if NOW[i - 1] < 0 and NOW[i] == 0:
		ANS += score + 1
		score = 0
print(ANS)


n = int(input())
s = list(input())
t = [0, 0]
for x in s:
	if x == '(':
		t[0] += 1
	else:
		t[1] += 1
if t[0] != t[1]:
	print(-1)
	exit(0)
else:
	mode = -1
	prev = -1
	left = 0
	right = 0
	tmp = 0
	ans = 0
	for (i, x) in enumerate(s):
		if x == '(':
			left += 1
		else:
			right += 1
		if right > left and prev < 0:
			prev = i
		elif right == left and prev >= 0:
			ans += i - prev + 1
			prev = -1
	print(ans)


def reorder(x):
	left = 0
	s = 0
	j = 0
	for i in x:
		if i == ')':
			left += 1
		elif i == '(':
			left -= 1
			if left == 0:
				s += j + 1
				j = 0
		if left > 0:
			j += 1
	if left != 0:
		return -1
	else:
		return s
l = int(input())
x = input()
print(reorder(x))


import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
M = 1000000007

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
n = Int()
s = input()
o = 0
c = 0
stack = 0
ans = 0
ok = True
for i in s:
	if i == '(':
		o += 1
		stack += 1
	if i == ')':
		c += 1
		if stack == 0:
			ok = False
		stack -= 1
	if o == c:
		if not ok:
			ans += o + c
		ok = True
		stack = 0
		o = 0
		c = 0
if stack != 0:
	ans = -1
print(ans)


n = int(input())
l = list(map(str, input().strip()))
b = 0
f = 0
c = 0
for i in range(n):
	if l[i] == ')':
		if f > 0:
			f -= 1
		else:
			b += 1
	if l[i] == '(':
		if b > 0:
			c += 1
			b -= 1
		else:
			f += 1
if f == 0 and b == 0:
	print(2 * c)
else:
	print(-1)


n = input()
n = int(n)
string = input()
o = 0
c = 0
temp = 0
ok = False
cnt = 0
for i in range(len(string)):
	if string[i] == '(':
		temp += 1
		o += 1
	if string[i] == ')':
		temp -= 1
		c += 1
	if temp < 0:
		cnt += 1
		ok = True
	if temp == 0 and ok:
		cnt += 1
		ok = False
if o != c:
	print('-1')
else:
	print(cnt)


n = int(input())
s = input()
(o, c) = (0, 0)
for i in s:
	if i == '(':
		o += 1
	else:
		c += 1
if o != c:
	print(-1)
	exit()
stk = [s[0]]
if s[0] == '(':
	o = 1
	c = 0
else:
	o = 0
	c = 1
ans = 0
for i in range(1, n):
	if s[i] == ')' and (len(stk) > 0 and stk[-1] == '('):
		stk.pop()
		c += 1
	elif s[i] == ')':
		stk.append(s[i])
		c += 1
	elif s[i] == '(':
		stk.append(s[i])
		o += 1
	if len(stk) == 0:
		(o, c) = (0, 0)
	if o == c:
		ans += 2 * o
		o = 0
		c = 0
		stk = []
print(ans)


from itertools import accumulate
n = int(input())
s = str(input())
if n % 2 == 1:
	print(-1)
elif s.count('(') != s.count(')'):
	print(-1)
else:
	x = 0
	y = 0
	b = []
	for _ in range(n):
		if s[_] == '(':
			b.append(1)
		else:
			b.append(-1)
	k = 0
	c = list(accumulate(b))
	d = [[0, -1]]
	for _ in range(1, len(c)):
		if c[_] == 0:
			if c[_ - 1] == -1:
				d.append([_ + 1, -1])
			else:
				d.append([_ + 1, 1])
	for _ in range(1, len(d)):
		if d[_][1] == -1:
			k += d[_][0] - d[_ - 1][0]
	print(k)


from sys import stdin, stdout

def check(vals):
	stack = []
	for j in vals:
		if j == '(':
			stack.append(j)
		else:
			if not stack:
				return False
			stack.pop()
	if stack:
		return False
	return True
t = 1
for _ in range(t):
	n = int(input())
	s = input()
	a = 0
	for i in s:
		if i == '(':
			a += 1
		else:
			a -= 1
	if a != 0:
		print(-1)
		continue
	vals = []
	ans = 0
	for i in s:
		if i == '(':
			a += 1
			vals.append('(')
		else:
			a -= 1
			vals.append(')')
		if a == 0 and len(vals):
			if not check(vals):
				ans += len(vals)
			vals = []
	print(ans)


import math
from math import sqrt
import sys
from functools import reduce
from collections import defaultdict

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())
mod = int(1000000000.0) + 7

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
n = iinput()
s = input()
ans = 0
faulty = 0
normal = 0
stk = []
top = -1
for i in s:
	if faulty != 0:
		if i == '(':
			faulty -= 1
		else:
			faulty += 1
		ans += 1
	elif normal == 0:
		if i == ')':
			faulty += 1
			ans += 1
		else:
			normal += 1
	elif i == ')':
		normal -= 1
	else:
		normal += 1
if n % 2 or s.count('(') != s.count(')'):
	print(-1)
else:
	print(ans)


input()
s = input()
counter = 0
value = 0
ans = 0
(left, right) = (0, 0)
for v in s:
	old_value = value
	if v == ')':
		right += 1
		value -= 1
	else:
		value += 1
		left += 1
	if value < 0 or old_value < 0:
		ans += 1
if left != right:
	print(-1)
else:
	print(ans)


n = int(input())
s = input()
open = 0
close = 0
ans = 0
if s.count('(') != s.count(')'):
	print(-1)
else:
	for i in range(n):
		if s[i] == '(':
			open += 1
		else:
			close += 1
			if open >= close:
				close -= 1
				open -= 1
			else:
				ans += 2
	print(ans)


n = int(input())
s = input()
arr = list(s)
count = 0
su = 0
p = -1
if n % 2 != 0:
	print(-1)
elif arr.count('(') != arr.count(')'):
	print(-1)
else:
	for k in range(n):
		if arr[k] == ')':
			count -= 1
		else:
			count += 1
		if count < 0 and p == -1:
			p = k
		elif count == 0 and p != -1:
			su += k - p + 1
			p = -1
	print(su)


n = int(input())
s = input()
cnt = 0
l = 0
ans = 0
(cntl, cntr) = (0, 0)
for i in s:
	if i == ')':
		cnt -= 1
		cntl += 1
		if cnt < 0:
			ans += 1
	else:
		cnt += 1
		cntr += 1
		if cnt <= 0:
			ans += 1
print(ans if cntl == cntr else -1)


(n, s) = (int(input()), input())
(a, r) = (0, 0)
for _ in s:
	a += -1 if _ == ')' else 1
	if a < 0 or (a == 0 and _ == '('):
		r += 1
print(r if a == 0 else -1)


n = int(input().strip())
arr = list(input().strip())
for i in range(n):
	if arr[i] == '(':
		arr[i] = 1
	else:
		arr[i] = -1
ans = 0
counter = 0
temp = 0
is_correct = True
for i in range(n):
	counter += arr[i]
	temp += 1
	if counter == 0:
		if not is_correct:
			ans += temp
			is_correct = True
		temp = 0
	elif counter < 0:
		is_correct = False
if counter:
	print(-1)
else:
	print(ans)


try:
	n = int(input())
	s = input()
	open1 = s.count('(')
	close = s.count(')')
	if open1 != close:
		print('-1')
	else:
		count = 0
		open2 = 0
		for i in range(n):
			if s[i] == ')':
				count += 1
				open2 += 1
			elif s[i] == '(' and open2 > 0:
				count += 1
				open2 -= 1
			else:
				count -= 1
				open2 -= 1
		print(count - open2)
except:
	pass


n = int(input())
l = input()
e = []
p = 0
for i in l:
	if i == '(':
		p += 1
		e.append(p)
	else:
		p -= 1
		e.append(p)
if e[-1] != 0:
	print(-1)
else:
	ans = 0
	z = 0
	for i in range(n):
		if e[i] < 0:
			z += 1
		elif z > 0:
			ans += z + 1
			z = 0
	print(ans)


n = int(input().strip())
s = input().strip()
ans = 0
ba = 0
if n == 1:
	print(-1)
else:
	stack = []
	stack.append((s[0], 0))
	if s[0] == '(':
		ba += 1
	else:
		ba -= 1
	for i in range(1, n):
		if s[i] == ')':
			if stack == [] or stack[-1][0] != '(':
				stack.append((s[i], i))
			else:
				stack.pop()
			ba -= 1
		else:
			stack.append((s[i], i))
			ba += 1
		if ba == 0 and stack != []:
			ans += i - stack[0][1] + 1
			stack = []
	if ba != 0:
		print(-1)
	else:
		print(ans)


n = int(input())
s = input()
ans = 0
low = 0
total = 0
for high in range(n):
	if s[high] == '(':
		total += 1
	else:
		total -= 1
	if total == 0:
		if s[low] == ')':
			ans += high - low + 1
		low = high + 1
		total = 0
if total != 0:
	print(-1)
else:
	print(ans)


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict as dd, deque as dq
import math, string

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
MOD = 10 ** 9 + 7

def solve():
	N = getInt()
	S = getStr()
	ans = 0
	curr = 0
	for i in range(N):
		if S[i] == '(':
			curr += 1
		else:
			curr -= 1
			if curr < 0:
				ans += 2
	if curr != 0:
		return -1
	return ans
print(solve())


(n, s, be, ans, l, r) = (int(input()), input(), 0, 0, 0, 0)
if s.count('(') != s.count(')'):
	exit(print(-1))
for (j, i) in enumerate(s):
	if i == '(':
		l += 1
	elif l:
		l -= 1
	else:
		r += 1
	if l == r:
		if l:
			ans += j - be + 1
		l = r = 0
		be = j + 1
print(ans)


n = int(input())
s = input().strip()
wc = 0
a = []
for (i, z) in enumerate(s):
	if z == ')':
		wc -= 1
	else:
		wc += 1
	a.append(wc)
if a[-1] != 0:
	print(-1)
	exit(0)
cnt = 0
bf = []
grz = []
for (i, z) in enumerate(a):
	if z != 0:
		bf.append(z)
	else:
		if bf[0] < 0:
			cnt += len(bf) + 1
		bf = []
print(cnt)


n = int(input())
s = input()
y = 0
ans = 0
for i in range(n):
	if s[i] == '(':
		if y == -1:
			ans += 1
		y += 1
	else:
		y -= 1
	if y < 0:
		ans += 1
if y == 0:
	print(ans)
else:
	print(-1)


p = int(input())
q = input()
x = q.count(')')
y = q.count('(')
c = 0
l = 0
r = 0
z = 0
sum = 0
if x != y:
	print(-1)
	c = 1
if c == 0:
	for i in range(p):
		if q[i] == '(':
			l += 1
		else:
			r += 1
		if r > l:
			z = 1
		if l == r and z == 0:
			l = 0
			r = 0
		if l == r and z == 1:
			sum += l + r
			l = 0
			r = 0
			z = 0
	print(sum)


n = int(input().strip())
ls = input().strip()
op = 0
cost = 0
index = 0
startsub = False
for i in range(len(ls)):
	if ls[i] == ')':
		op -= 1
	else:
		op += 1
	if not startsub and op < 0:
		index = i
		startsub = True
	if startsub and op == 0:
		cost += i - index + 1
		startsub = False
if op:
	print(-1)
else:
	print(cost)


n = int(input())
arr = input()
validity = [0]
count = 0
if len(arr) % 2 != 0:
	print(-1)
	exit(0)
if arr.count('(') != arr.count(')'):
	print(-1)
	exit(0)
for i in range(len(arr)):
	if arr[i] == '(':
		count += 1
	else:
		count -= 1
	if count == 0:
		validity.append(i + 1)
sub = []
for i in range(len(validity) - 1):
	sub.append(arr[validity[i]:validity[i + 1]])
count = 0
for j in range(len(sub)):
	s = sub[j]
	stack = []
	for i in range(len(s)):
		if not stack:
			if s[i] == ')':
				count += len(s)
				break
			else:
				stack.append(arr[i])
		elif s[i] == ')':
			stack.pop()
		else:
			stack.append('(')
		if i == len(s) - 1:
			if stack:
				count += len(s)
print(count)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
n = int(input())
brackets = input()
wrongbra = 0
(tl, tr) = (0, 0)
(l, r) = (0, 0)
wrongNow = False
for (i, bra) in enumerate(brackets):
	if bra == ')':
		r += 1
		tr += 1
	else:
		l += 1
		tl += 1
	if l < r:
		wrongNow = True
	if wrongNow:
		if l == r:
			wrongNow = False
			wrongbra += l + r
			(l, r) = (0, 0)
	elif l == r:
		(l, r) = (0, 0)
if tl != tr:
	print(-1)
else:
	print(wrongbra)


n = int(input())
string = input()
stack = []
c = 0
for x in string:
	if x == '(':
		c -= 1
		stack.append(c)
	else:
		c += 1
		stack.append(c)
if stack[-1]:
	print(-1)
else:
	prev = -1
	ans = 0
	for x in range(n):
		if stack[x] == 0:
			if stack[x - 1] == 1:
				ans += x - prev
			prev = x
	print(ans)


(n, lst) = (int(input()), list(input()))
if n % 2 or not lst.count('(') == lst.count(')'):
	print(-1)
else:
	(res, crnt, closed, opened) = (0, 0, 0, 0)
	for i in range(n):
		crnt += 1
		if lst[i] == ')':
			if opened - closed > 0:
				res -= 2
			closed += 1
		else:
			opened += 1
		if opened == closed:
			res += crnt
			(crnt, opened, closed) = (0, 0, 0)
	print(res)


from bisect import bisect_left as bl, bisect_right as br, insort
import sys
import heapq
from math import *
from collections import defaultdict as dd, deque

def data():
	return sys.stdin.readline().strip()

def mdata():
	return map(int, data().split())
n = int(data())
s = data()
l = []
o = c = 0
k = 0
ans = 0
for i in range(n):
	if s[i] == '(':
		o += 1
		l.append('(')
	else:
		c += 1
		if len(l) > 0:
			if l[-1] == '(':
				l.pop()
			else:
				l.append(')')
		else:
			l.append(')')
	if o == c and len(l) != 0:
		ans += o + c
		l = []
		o = c = 0
	if len(l) == 0:
		o = c = 0
if o != c:
	print(-1)
else:
	print(ans)


l = int(input())
li = input()
tmpli = []
zctr = 0
z1 = 0
z0 = 0
ans = 0
for (idx, i) in enumerate(li):
	if i == '(':
		tmpli.append(False)
		zctr += 1
		if zctr == 0:
			ans += len(tmpli)
			tmpli = []
		z1 += 1
	else:
		zctr -= 1
		tmpli.append(True)
		if zctr == 0:
			tmpli = []
		z0 += 1
if z1 == z0:
	print(ans)
else:
	print(-1)


from collections import Counter
n = int(input())
if n & 1:
	input()
	print(-1)
else:
	x = input()
	d = Counter(x)
	if d['('] != d[')']:
		print(-1)
	else:
		op = 0
		cl = 0
		c = 0
		for i in x:
			if i == '(':
				op += 1
			else:
				cl += 1
				if cl > op:
					c += 1
		print(c * 2)


(n, b, a, r) = (int(input()), input(), 0, 0)
for c in b:
	a += -1 if c == ')' else 1
	if a < 0 or (a == 0 and c == '('):
		r += 1
print(r if a == 0 else -1)


n = int(input())
p = input()
ans = 0
temp = 0
for i in p:
	if i == ')':
		temp -= 1
	else:
		temp += 1
		if temp == 0:
			ans += 1
	if temp < 0:
		ans += 1
if temp != 0:
	print(-1)
else:
	print(ans)


n = int(input())
s = input()
if s.count(')') != s.count('('):
	print(-1)
else:
	a = [1] * n
	if s[0] == ')':
		a[0] = -1
	for i in range(1, n):
		if s[i] == '(':
			a[i] = a[i - 1] + 1
		else:
			a[i] = a[i - 1] - 1
	i = 0
	time = 0
	while i < n:
		if a[i] < 0:
			j = i + 1
			while j < n:
				if a[j] == 0:
					time += j - i + 1
					break
				j += 1
			i = j + 1
		else:
			i += 1
	print(time)


n = int(input())
s = input()
c = 0
a = [0] * n
ans = 0
for i in range(n):
	if s[i] == '(':
		c += 1
		a[i] = c
	else:
		c -= 1
		a[i] = c
i = 0
j = 0
if a[-1] != 0:
	print(-1)
	exit()
while j < n:
	if a[j] == 0:
		if a[j - 1] < 0:
			ans += j - i + 1
			i = j + 1
		else:
			i = j + 1
	j += 1
if n % 2 == 0:
	print(ans)
else:
	print(-1)


n = int(input())
seq = list(input())
if seq.count(')') != seq.count('('):
	print(-1)
else:
	(a, b) = ([], [])
	for i in range(len(seq)):
		if seq[i] == ')':
			a.append(i)
		else:
			b.append(i)
	c = []
	for i in range(len(a)):
		if b[i] > a[i]:
			c.append(a[i])
			c.append(b[i])
	c.sort()
	start = 0
	sum = 0
	for i in range(len(c) - 1):
		if c[i] != c[i + 1] - 1:
			sum += c[i] - c[start] + 1
			start = i + 1
		elif i == len(c) - 2:
			sum += c[i + 1] - c[start] + 1
	print(sum)


from sys import stdin as sin

def aint():
	return int(input())

def amap():
	return map(int, sin.readline().split())

def alist():
	return list(map(int, sin.readline().split()))

def astr():
	return input()
n = aint()
s = input()
st = []
left = 0
right = 0
start = -1
ans = 0
for i in range(n):
	if s[i] == '(':
		left += 1
	else:
		right += 1
		if left < right:
			if start == -1:
				start = i
	if start != -1 and left == right:
		ans += i - start + 1
		start = -1
if left == right:
	print(ans)
else:
	print(-1)


import bisect
import collections
import copy
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
from typing import *
import operator
sys.setrecursionlimit(99999)

def check(s):
	k = 0
	for i in range(len(s)):
		if s[i] == '(':
			k += 1
		else:
			k -= 1
		if k < 0:
			return False
	return True

def solve(s):
	if check(s):
		return 0
	if s[0] == '(' and s[-1] == ')':
		return solve(s[1:len(s) - 1])
	return len(s)
n = int(input())
s = input()
if n & 1 or s.count('(') != n // 2:
	print('-1')
else:
	k = 0
	st = 0
	ans = 0
	for i in range(len(s)):
		if s[i] == '(':
			k += 1
		else:
			k -= 1
		if k == 0:
			ans += solve(s[st:i + 1])
			st = i + 1
	print(ans)


n = int(input())
s = input()
arr = [0]
for i in range(n):
	if s[i] == '(':
		arr.append(arr[-1] + 1)
	else:
		arr.append(arr[-1] - 1)
su = 0
if arr[-1] != 0:
	print(-1)
else:
	tmp = [i for i in range(len(arr)) if arr[i] == 0]
	for i in range(1, len(tmp)):
		if arr[tmp[i - 1] + 1] < 0:
			su += tmp[i] - tmp[i - 1]
	print(su)


n = int(input())
s = input()
s = [1 if i == '(' else -1 for i in s]
pr = [s[0]]
for i in s[1:]:
	pr.append(pr[-1] + i)
if pr[-1] != 0:
	print(-1)
else:
	ans = 0
	if pr[0] < 0:
		ans += 1
	for i in range(1, n):
		if pr[i] < 0 or (pr[i] == 0 and pr[i - 1] < 0):
			ans += 1
	print(ans)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = 1
	rr = []
	for _ in range(t):
		n = I()
		s = S()
		c = 0
		ci = 0
		r = 0
		for (i, t) in enumerate(s):
			if t == ')':
				c -= 1
				if c == -1:
					ci = i
			else:
				c += 1
				if c == 0:
					r += i - ci + 1
		rr.append(IF(c == 0, r, -1))
	return JA(rr, '\n')
print(main())


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
n = int(input())
s = [i == '(' for i in input()]
if n % 2 == 1 or sum(s) != n // 2:
	print(-1)
	exit()
ans = 0
i = 0
left = 0
right = 0
while i < n:
	if s[i]:
		left += 1
	else:
		right += 1
	if left < right:
		l = i
		i += 1
		while i < n:
			if s[i]:
				left += 1
			else:
				right += 1
			if left == right:
				ans += i - l + 1
				break
			i += 1
	i += 1
print(ans)


n = int(input())
s = input()
if n % 2 == 1:
	print(-1)
	exit()
l = 0
r = 0
flag = False
tmp = 0
ans = 0
for c in s:
	if c == '(':
		l += 1
	else:
		r += 1
	if r > l:
		flag = True
	if flag:
		tmp += 1
		if l == r:
			ans += tmp
			tmp = 0
			flag = False
if l == r:
	print(ans)
else:
	print(-1)


n = int(input())
s = input()
if n % 2 == 1 or s.count('(') != s.count(')'):
	print(-1)
	exit()
a = 0
nl = -1
nr = -1
ans = 0
for i in range(n):
	if s[i] == '(':
		a += 1
	else:
		a -= 1
	if a < 0:
		if nl <= -1:
			(nl, nr) = (i, i + 1)
		else:
			nr = i + 1
	elif nl != -1:
		ans += nr - nl + 1
		(nl, nr) = (-1, -1)
print(ans)


import sys, os
from io import BytesIO, IOBase
import collections, itertools, bisect, heapq, math, string
BUFSIZE = 8192
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def main():
	n = int(input())
	s = str(input())
	if n % 2 == 1:
		print(-1)
		return
	ans = 0
	x = 0
	for i in range(n):
		if s[i] == ')':
			x = x - 1
			if x < 0:
				ans = ans + 2
		else:
			x = x + 1
	if x != 0:
		print(-1)
	else:
		print(ans)
main()


(__, s) = (input(), input())
(a, n) = (0, 0)
chk = {'(': 1, ')': -1}
for i in s:
	k = chk.get(i, 0)
	if a < 0 or a + k < 0:
		n += 1
	a += k
if a != 0:
	print(-1)
else:
	print(n)


def compute_min(brackets):
	i = 0
	j = 0
	for b in brackets:
		if b == ')':
			j += 1
		else:
			i += 1
	if i != j:
		return -1
	factor = 0
	i = 0
	reorder_size = 0
	while i < len(brackets):
		if brackets[i] == ')':
			factor -= 1
		else:
			factor += 1
		i += 1
		if factor < 0:
			j = i
			while factor != 0:
				if brackets[j] == ')':
					factor -= 1
				else:
					factor += 1
				j += 1
			reorder_size += j - i + 1
			i = j
	return reorder_size
n = int(input())
brackets = input()
print(compute_min(brackets))


def main():
	for _ in range(1):
		n = int(input())
		s = input()
		if s.count('(') != s.count(')'):
			print(-1)
			return
		c1 = 0
		c2 = 0
		ans = 0
		for i in range(n):
			if s[i] == '(':
				c1 += 1
			else:
				c2 += 1
			if c1 == c2:
				if s[i] == '(':
					ans += c1 + c2
				c1 = c2 = 0
		print(ans)
main()


n = int(input())
s = list(input())
if s.count('(') != s.count(')'):
	print(-1)
else:
	x = 0
	length = 0
	cnt = 0
	for i in s:
		if i == ')':
			x -= 1
			length += 1
			if x == 0:
				length = 0
		else:
			x += 1
			length += 1
			if x == 0:
				cnt += length
				length = 0
	print(cnt)


n = int(input())
a = input()
c = a.count('(')
if c != n - c:
	print(-1)
else:
	temp = ans = 0
	j = -1
	en = 1
	for i in range(n):
		if a[i] == '(':
			temp += 1
		else:
			temp -= 1
		if temp < 0 and en:
			j = i
			en = 0
		if temp == 0 and j != -1:
			ans += i - j + 1
			j = -1
			en = 1
	print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
n = int(input())
seq = input()
lbr = []
cl = 0
rbr = []
cr = 0
diff = []
for j in range(n):
	if seq[j] == '(':
		cl += 1
	else:
		cr += 1
	lbr.append(cl)
	rbr.append(cr)
	diff.append(cl - cr)
if cr != cl:
	print(-1)
else:
	cont = 0
	outy = 0
	for j in range(n):
		if diff[j] < 0:
			cont += 1
		elif diff[j] == 0:
			if cont > 0:
				outy += cont + 1
				cont = 0
	if cont > 0:
		outy += cont + 1
	print(outy)


def solve(S):
	res = s = 0
	last_non_neg = -2
	for (i, c) in enumerate(S):
		s += 1 if c == '(' else -1
		if s < 0:
			if last_non_neg == -2:
				last_non_neg = i - 1
		elif s == 0:
			if last_non_neg != -2:
				res += i - last_non_neg
			last_non_neg = -2
	return res if s == 0 else -1
input()
s = input().strip()
print(solve(s))


t = int(input())
l = list(input())
e = 0
d = 0
c = 0
for i in range(t):
	if l[i] == '(':
		if e > d:
			c += 2
		d += 1
	if l[i] == ')':
		e += 1
if e != d:
	print(-1)
else:
	print(c)


n = int(input())
s = input()
if s.count(')') != s.count('('):
	print(-1)
	exit(0)
ans = 0
ct = 0
st = -1
f = 0
for i in range(n):
	if s[i] == '(':
		ct += 1
	else:
		ct -= 1
	if ct == 0:
		if f == -1:
			ans += i - st
		f = 0
		ct = 0
		st = i
	if ct < 0:
		f = -1
print(ans)


n = int(input())
seq = input()
t = 0
n = 0
wn = False
l = 0
for s in seq:
	l += 1
	if s == ')':
		t -= 1
	else:
		t += 1
	if t < 0:
		wn = True
	if t == 0:
		if wn:
			wn = False
			n += l
		l = 0
if t:
	print(-1)
else:
	if wn == False:
		n += l
	print(n)


def main():
	import sys
	input = sys.stdin.readline
	N = int(input())
	S = input().rstrip('\n')
	T = [0] * N
	for (i, s) in enumerate(S):
		if s == '(':
			T[i] = 1
		else:
			T[i] = -1
	if sum(T) != 0:
		print(-1)
		exit()
	for i in range(1, N):
		T[i] += T[i - 1]
	ans = 0
	cnt = 0
	for t in T:
		if t < 0:
			cnt += 1
		else:
			if cnt:
				ans += cnt + 1
			cnt = 0
	print(ans)
main()


import sys

def main(n, s):
	if s.count('(') != s.count(')'):
		return -1
	res = 0
	stk = []
	(l_cnt, r_cnt) = (0, 0)
	for (i, c) in enumerate(s):
		if c == '(':
			l_cnt += 1
			stk.append('(')
		else:
			r_cnt += 1
			if stk and stk[-1] == '(':
				stk.pop()
			else:
				stk.append(')')
		if l_cnt == r_cnt:
			if stk:
				res += l_cnt + r_cnt
				stk = []
			(l_cnt, r_cnt) = (0, 0)
	return res
n = int(input())
s = input()
res = main(n, s)
print(res)


n = int(input())
s = input()
if s.count('(') == s.count(')'):
	ls = []
	temp = 0
	for i in range(n):
		if s[i] == '(':
			temp += 1
		else:
			temp -= 1
		ls.append(temp)
	ans = 0
	count = 0
	for i in range(n):
		if ls[i] < 0:
			count += 1
		elif ls[i] == 0 and count:
			ans += count + 1
			count = 0
	print(ans)
else:
	print(-1)


n = int(input())
seq = input()
count = 0
reorder = 0
for c in seq:
	if c == '(':
		count += 1
	else:
		count -= 1
		if count < 0:
			reorder += 1
if count != 0:
	print(-1)
else:
	print(reorder * 2)


def checker(n, s):
	l = 0
	r = 0
	i = 0
	ans = 0
	while i < n:
		while s[i] == '(':
			if l != 0:
				l -= 1
				i += 1
			else:
				r += 1
				i += 1
			if i == n:
				break
		if i == n:
			break
		while s[i] == ')':
			l += 1
			if l > r:
				ans += 1
			else:
				r -= 1
				l -= 1
			i += 1
			if i == n:
				break
	if l != 0 or r != 0:
		return -1
	else:
		return 2 * ans
n = int(input())
s = str(input())
print(checker(n, s))


def checker(n, s):
	if n % 2 == 1 or s.count(')') != s.count('('):
		return -1
	(count1, count2, flag) = (0, 0, 0)
	for i in range(n):
		if s[i] == '(':
			count1 += 1
		else:
			count1 -= 1
		if count1 == 0:
			flag = 0
		if count1 < 0:
			count2 += 1
			if flag == 0:
				count2 += 1
				flag = 1
	return count2
m = int(input())
t = input()
print(checker(m, t))


import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
from math import *
import copy
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

def li():
	return [int(x) for x in input().split()]

def fi():
	return int(input())

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def bo(i):
	return ord(i) - ord('a')
from copy import *
from bisect import *
from itertools import permutations
t = 1
while t > 0:
	t -= 1
	n = fi()
	s = si()
	o = c = ans = 0
	for i in range(n):
		if s[i] == '(':
			if c > 0:
				c -= 1
				ans += 2
			else:
				o += 1
		elif o > 0:
			o -= 1
		else:
			c += 1
	print(ans if c == 0 and o == 0 else -1)


n = int(input())
s = str(input())
if n % 2 == 1 or s.count('(') != n // 2:
	print(-1)
	exit()
ans = 0
l = 0
bad = False
count = 0
for i in range(n):
	if s[i] == '(':
		count += 1
		if bad and count == 0:
			ans += i - l + 1
			bad = False
	else:
		if count == 0:
			l = i
			bad = True
		count -= 1
print(ans)


import math, sys
from collections import Counter, defaultdict, deque
from sys import stdin, stdout
input = stdin.readline
li = lambda : list(map(int, input().split()))

def case():
	n = int(input())
	s = input().strip()
	if n % 2 != 0:
		print(-1)
		exit()
	a = []
	c = 0
	for i in range(0, n):
		if s[i] == '(':
			if len(a) != 0 and a[-1] == ')':
				c += 2
				a.pop()
			else:
				a.append('(')
		elif len(a) != 0 and a[-1] == '(':
			a.pop()
		else:
			a.append(')')
	if len(a) != 0:
		print(-1)
	else:
		print(c)
for _ in range(1):
	case()


n = int(input())
s = str(input())
(count, count2, err, ans) = (0, 0, 0, 0)
for i in range(n):
	if s[i] == '(':
		count += 1
	else:
		count2 += 1
	if count < count2:
		err = 1
	if count == count2:
		if err == 1:
			ans += count + count2
		(count, count2, err) = (0, 0, 0)
if count != count2:
	print(-1)
else:
	print(ans)


n = int(input())
a = list(input())
ans = 0
x = a.count('(')
y = a.count(')')
if x != y:
	print(-1)
else:
	(c, f) = (0, 0)
	(start, time) = (0, 0)
	for i in range(n):
		if a[i] == '(':
			c += 1
		else:
			c -= 1
		if f == 1 and c == 0:
			time += i - start + 1
			f = 0
		if c < 0 and f == 0:
			start = i
			f = 1
	print(time)


length = int(input())
brackets = input()
left = 0
right = 0
for i in brackets:
	if i == '(':
		left += 1
	else:
		right += 1
if left == right:
	left = 0
	right = 0
	counter = 0
	start = brackets[0]
	time = 0
	for i in range(0, length):
		if brackets[i] == '(':
			left += 1
		else:
			right += 1
		d = left - right
		counter += 1
		if d == 0:
			if start == ')':
				time += counter
			else:
				counter = 0
			if i != length - 1:
				start = brackets[i + 1]
			counter = 0
	print(time)
else:
	print(-1)


n = int(input())
s = input()
(o, c) = (0, 0)
ss = 0
for i in s:
	if i == ')':
		c += 1
	else:
		o += 1
		if c >= o:
			ss += 2
if o == c:
	print(ss)
else:
	print(-1)


import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub
sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2 ** 62 - 1

def read_int():
	return int(input())

def read_int_n():
	return list(map(int, input().split()))

def read_float():
	return float(input())

def read_float_n():
	return list(map(float, input().split()))

def read_str():
	return input().strip()

def read_str_n():
	return list(map(str, input().split()))

def error_print(*args):
	print(*args, file=sys.stderr)

def mt(f):
	import time

	def wrap(*args, **kwargs):
		s = time.time()
		ret = f(*args, **kwargs)
		e = time.time()
		error_print(e - s, 'sec')
		return ret
	return wrap

@mt
def slv(N, S):
	c = Counter(S)
	if c['('] != c[')']:
		return -1
	l = 0
	r = 0
	x = None
	ans = 0
	for i in range(N):
		if S[i] == '(':
			l += 1
		else:
			r += 1
		if x is None and r > l:
			x = i
		if x is not None and l == r:
			ans += i - x + 1
			x = None
	return ans

def main():
	N = read_int()
	S = [c for c in read_str()]
	print(slv(N, S))
main()


n = int(input())
a = input()
cnt = 0
for i in range(n):
	if a[i] == '(':
		cnt += 1
r = 0
if cnt == n >> 1:
	cnt = 0
	i = 0
	while i < n:
		if a[i] == ')':
			cnt -= 1
		else:
			cnt += 1
		if cnt < 0:
			for j in range(i + 1, n):
				if a[j] == ')':
					cnt -= 1
				else:
					cnt += 1
				if not cnt:
					r += j - i + 1
					i = j
					break
		i += 1
	if cnt:
		print(-1)
	else:
		print(r)
else:
	print(-1)


import sys
n = int(input())
s = input()
if n % 2 == 1:
	print(-1)
	sys.exit(0)
cnt = 0
for i in range(n):
	if s[i] == '(':
		cnt += 1
if cnt != n - cnt:
	print(-1)
	sys.exit(0)
cur = 0
cnt = 0
last = 0
for i in range(n):
	if s[i] == '(':
		cur += 1
	else:
		cur -= 1
	if cur < 0:
		cnt += 1
	if last < 0 and cur == 0:
		cnt += 1
	last = cur
print(cnt)


from sys import stdin
from math import ceil
n = int(stdin.readline())
s = stdin.readline().strip()
if n % 2 == 0 and s.count('(') == s.count(')'):
	count = 0
	ans = []
	start = 0
	val = 0
	for i in range(n):
		if s[i] == ')':
			val -= 1
			ans.append(val)
		else:
			val += 1
			ans.append(val)
	j = 0
	while start < n:
		if ans[start] < 0:
			j += 1
		if ans[start] == 0:
			if j > 0:
				count += j + 1
				j = 0
		start += 1
	print(count)
else:
	print(-1)


n = int(input())
s = input()
if s.count('(') != s.count(')'):
	print(-1)
else:
	left = 0
	right = 0
	is_correct = 1
	start = 0
	cnt = 0
	for (i, ch) in enumerate(s):
		if ch == '(':
			left += 1
		else:
			right += 1
		if right > left:
			is_correct = 0
		if left == right and is_correct:
			left = 0
			right = 0
			is_correct = 1
			start = i + 1
		if left == right and (not is_correct):
			cnt += i - start + 1
			start = i + 1
			left = 0
			right = 0
			is_correct = 1
	print(cnt)


n = int(input())
s = input()
st = []
co = 0
cc = 0
res = 0
for i in range(n):
	if s[i] == ')':
		cc += 1
		if len(st) and st[-1] == '(':
			st.pop()
		else:
			st.append(s[i])
		if len(st) == 0:
			cc = 0
			co = 0
	if s[i] == '(':
		st.append(s[i])
		co += 1
	if cc == co and len(st):
		res += cc + co
		st = []
		cc = 0
		co = 0
if len(st):
	print(-1)
else:
	print(res)


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools
from collections import deque, defaultdict, OrderedDict
import collections

def main():
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	mod = 998244353
	for _ in range(1):
		n = ri()
		s = rs()
		z = []
		depth = 0
		op = 0
		cl = 0
		ans = 0
		for i in s:
			k = depth
			if i == '(':
				depth += 1
				op += 1
			else:
				depth -= 1
				cl += 1
			if depth < 0 or k < 0:
				ans += 1
		if op != cl:
			wi(-1)
		else:
			wi(ans)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


n = int(input())
s = input()
c1 = 0
c2 = 0
ans = 0
for i in range(len(s)):
	if s[i] == ')':
		c1 = c1 + 1
	else:
		c2 = c2 + 1
		if c1 >= c2:
			ans = ans + 2
if c1 == c2:
	print(ans)
else:
	print(-1)


n = int(input())
s = input()
a = [0 for _ in range(n)]
ans = 0
k = 0
if s[0] == '(':
	a[0] = 1
else:
	a[0] = -1
	ans += 1
for i in range(1, n):
	if s[i] == '(':
		a[i] += a[i - 1] + 1
		if a[i] < 0:
			ans += 1
	else:
		a[i] += a[i - 1] - 1
		if a[i] < 0:
			ans += 1
a = [0] + a
for i in range(n + 1):
	if a[i] == 0 and i != n and (a[i + 1] < 0):
		k += 1
if a[n] != 0:
	print(-1)
else:
	print(k + ans)


n = int(input())
arr = list(input())
sol = [0]
for i in range(n):
	if arr[i] == ')':
		sol.append(sol[-1] - 1)
	else:
		sol.append(sol[-1] + 1)
store = 0
cost = 0
for i in range(1, n + 1):
	if sol[i] == -1 and sol[i - 1] == 0:
		store = i
	elif sol[i] == 0 and sol[i - 1] == -1:
		cost += i - store + 1
if sol[-1] != 0:
	print(-1)
else:
	print(cost)


from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def smp():
	return map(str, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
n = iinp()
s = inp()
c = 0
ans = 0
if s.count('(') != s.count(')'):
	print(-1)
	exit()
for i in s:
	if i == ')':
		if c <= 0:
			ans += 1
		c -= 1
	else:
		if c < 0:
			ans += 1
		c += 1
print(ans)


n = int(input())
s = input()
a = 0
b = 0
for i in range(0, len(s)):
	if s[i] == ')':
		a += 1
	else:
		b += 1
if a != b:
	print(-1)
else:
	count = 0
	stack = []
	i = 0
	while i < len(s):
		a = 0
		b = 0
		if s[i] == '(':
			stack.append(s[i])
		elif stack == []:
			for j in range(i, len(s)):
				if s[j] == ')':
					a += 1
				else:
					b += 1
				if a == b:
					k = j
					break
			count = count + k + 1 - i
			i = k
		else:
			stack.pop(-1)
		i += 1
	print(count)


n = int(input())
s = list(input())
count = 0
ans = 0
for i in s:
	if i == '(':
		if count < 0:
			ans += 2
		count += 1
	else:
		count -= 1
if count == 0:
	print(ans)
else:
	print(-1)


n = int(input())
s = input()
count_1 = s.count(')')
count_2 = s.count('(')
counter = 0
count = 0
i = 0
if count_1 == count_2:
	for i in range(len(s)):
		if s[i] == ')':
			counter = counter - 1
		else:
			counter = counter + 1
		if counter < 0:
			flag = 0
			count = count + 1
		elif counter == 0 and flag == 0:
			count = count + 1
		else:
			flag = 1
	print(count)
else:
	print(-1)


n = int(input())
s = input()
ans = 0
count = 0
for x in s:
	pre = count
	if x == ')':
		count -= 1
	else:
		count += 1
	if count < 0:
		ans += 1
	if count == 0 and pre < 0:
		ans += 1
if count == 0:
	print(ans)
else:
	print(-1)


n = int(input())
braces = input()
open_nr = braces.count('(')
closed_nr = braces.count(')')
ans = 0
if open_nr != closed_nr:
	print(-1)
else:
	balance = 0
	balances = []
	for brace in braces:
		if brace == '(':
			balance += 1
		elif brace == ')':
			balance -= 1
		else:
			raise
		balances.append('+' if balance >= 0 else '-')
	ans = sum((len(seg) + 1 for seg in ''.join(balances).split('+') if seg))
	print(ans)


n = int(input())
s = list(input())
o = s.count('(')
c = s.count(')')
if o != c:
	print('-1')
	exit()
o = 0
c = 0
flag = 0
cnt = 0
ans = 0
for i in range(len(s)):
	if s[i] == '(':
		o += 1
	else:
		o -= 1
	if flag == 0 and o < 0:
		flag = 1
		cnt = 1
	elif flag == 1 and o < 0:
		cnt += 1
	elif flag == 1 and o == 0:
		ans += cnt + 1
		cnt = 0
		flag = 0
ans += cnt
print(ans)


n = int(input())
s = input()
c0 = s.count('(')
c1 = s.count(')')
if c0 != c1:
	print(-1)
else:
	c = 0
	l = 0
	r = 0
	for j in range(n):
		if s[j] == '(':
			l += 1
		else:
			r += 1
		if l == r:
			if s[j] == '(':
				c += l * 2
				l = 0
				r = 0
			else:
				l = 0
				r = 0
	print(c)


x = int(input())
n = input()
k = 0
lol = []
p = 0
q = 0
for i in range(x):
	if n[i] == ')':
		k += 1
		p += 1
	else:
		k -= 1
		q += 1
	lol.append(k)
k = 0
if p != q:
	print(-1)
else:
	ans = 0
	for i in range(x):
		if lol[i] == 0:
			if lol[i - 1] > 0:
				ans += i + 1 - k
			k = i + 1
	print(ans)


def solve(n, s):
	i = 0
	ans = 0
	while i < n:
		cnt = s[i]
		j = i + 1
		while j < n and cnt != 0:
			cnt += s[j]
			j += 1
		if s[i] == -1:
			ans += j - i
		i = j
	return ans

def main():
	n = int(input())
	s = [1 if x == '(' else -1 for x in input()]
	if sum(s) != 0:
		print(-1)
	else:
		print(solve(n, s))
main()


import sys
input = sys.stdin.readline

def fastio():
	from io import StringIO
	from atexit import register
	global input
	sys.stdin = StringIO(sys.stdin.read())
	input = lambda : sys.stdin.readline().rstrip('\r\n')
	sys.stdout = StringIO()
	register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
INF = 10 ** 20
MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br
(n,) = I()
s = input()
s = [1 if i == '(' else -1 for i in s]
if sum(s) != 0:
	print(-1)
	exit()
ans = 0
odd = False
last = 0
if s[0] == -1:
	odd = 1
for i in range(1, n):
	s[i] += s[i - 1]
for i in range(n):
	if s[i] == -1 and (not odd):
		odd = 1
		last = i
	if s[i] == 0 and odd:
		ans += i - last + 1
		last = 0
		odd = 0
print(ans)


n = int(input())
s = input()
c = 0
c1 = 0
ans = 0
start = 0
t = -1
f = 0
for i in range(n):
	if s[i] == '(':
		c += 1
	else:
		c1 += 1
		if c1 > c and t == -1:
			t = i
	if c == c1 and c != 0 and (t != -1):
		f = 1
		ans += i - t + 1
		t = -1
		c = 0
		c1 = 0
if c1 == c and c1 != 0 and (f == 0):
	print(0)
elif c1 != c:
	print(-1)
else:
	print(ans)


true_stack = []
wrong_stack = []
is_wrong = False
wrong_length = 0
n = int(input())
string = input()
if n % 2 == 1:
	print(-1)
else:
	for i in range(n):
		if string[i] == '(' and (not is_wrong):
			true_stack.append('(')
		elif string[i] == '(':
			wrong_stack.pop()
			wrong_length += 2
			if len(wrong_stack) == 0:
				is_wrong = False
		elif string[i] == ')' and (not is_wrong):
			if len(true_stack) == 0:
				is_wrong = True
				wrong_stack.append(')')
			else:
				true_stack.pop()
		else:
			wrong_stack.append(')')
	if len(wrong_stack) != 0 or len(true_stack) != 0:
		print(-1)
	else:
		print(wrong_length)


def main_function():
	n = int(input())
	s = list(input())
	counter_1 = 0
	counter_2 = 0
	for i in s:
		if i == ')':
			counter_2 += 1
		else:
			counter_1 += 1
	if counter_1 != counter_2:
		print(-1)
	else:
		is_started = False
		one_counter = 0
		another_counter = 0
		final_counter = 0
		if n % 2 == 1:
			print(-1)
		else:
			for i in range(n):
				if s[i] == '(':
					one_counter += 1
				else:
					one_counter -= 1
				if not is_started:
					if one_counter < 0:
						another_counter = 1
						is_started = True
				else:
					another_counter += 1
					if one_counter < 0:
						pass
					else:
						final_counter += another_counter
						another_counter = 0
						is_started = False
			print(final_counter)
main_function()


def func(arr, num, temp, total_time, index):
	while index < n:
		if arr[index] == '(':
			num += 1
		else:
			num -= 1
		if num == 0 and temp == 0:
			index += 1
		elif num > 0:
			index += 1
			continue
		elif num < 0:
			index += 1
			temp += 1
			continue
		elif num == 0 and temp > 0:
			total_time += temp + 1
			index += 1
			num = 0
			temp = 0
	if num == 0:
		return total_time
	else:
		return -1
n = int(input())
string = input()
arr = []
for i in range(n):
	arr.append(string[i])
(num, temp, index, total_time) = (0, 0, 0, 0)
if n % 2 == 0:
	print(func(arr, num, temp, total_time, index))
else:
	print(-1)


input()
s = input()
count = 0
ans = 0
length = 0
for c in s:
	if c == '(':
		count += 1
		length += 1
		if count == 0:
			ans += length
			length = 0
	else:
		count -= 1
		length += 1
		if count == 0:
			length = 0
print(ans if count == 0 else -1)


n = int(input())
s = input()
res = 0
cur = 0
l = 0
need_reorder = False
for i in s:
	if i == ')':
		cur -= 1
		if cur < 0:
			need_reorder = True
	if need_reorder:
		l += 1
	if i == '(':
		cur += 1
		if cur == 0 and need_reorder:
			res += l
			l = 0
			need_reorder = False
if cur != 0:
	print(-1)
else:
	print(res)


n = int(input())
seq = input()
itr = 0
count1 = 0
count2 = 0
for i in seq:
	if i == '(':
		count1 = count1 + 1
	else:
		count2 = count2 + 1
if count1 != count2:
	print(-1)
else:
	ans = 0
	i = 0
	while i < n:
		count1 = 0
		count2 = 0
		if seq[i] == '(':
			count1 = count1 + 1
			i = i + 1
			while count1 != 0 and i < n:
				if seq[i] == '(':
					count1 = count1 + 1
				else:
					count1 = count1 - 1
				i = i + 1
		else:
			length = 1
			count2 = count2 + 1
			i = i + 1
			while count2 != 0 and i < n:
				if seq[i] == ')':
					count2 = count2 + 1
				else:
					count2 = count2 - 1
				i = i + 1
				length = length + 1
			ans = ans + length
	print(ans)


n = int(input())
str = input()
if n % 2 == 1:
	print(-1)
else:
	arr = [-1 if i == ')' else 1 for i in str]
	if sum(arr) != 0:
		print(-1)
	else:
		c = 0
		i = -1
		tc = 0
		for (j, a) in enumerate(arr):
			c += a
			if c == 0:
				if a > 0:
					tc += j - i
				i = j
		print(tc)


n = int(input())
s = input()
output = 0
count = 0
if s.count('(') != s.count(')'):
	print(-1)
else:
	for i in range(n):
		last = count
		if s[i] == '(':
			count += 1
		else:
			count += -1
		if count < 0 or last < 0:
			output += 1
	print(output)


import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def main():
	n = II()
	s = SI()
	aa = []
	a = 0
	for c in s:
		if c == '(':
			a += 1
		else:
			a -= 1
		aa.append(a)
	if aa[-1] != 0:
		print(-1)
		exit()
	pa = 1
	ans = 0
	for a in aa:
		if a < 0:
			ans += 1
		elif pa < 0:
			ans += 1
		pa = a
	print(ans)
main()


from sys import stdin
input = stdin.readline
n = int(input())
s = input()[:-1]
a = ans = 0
for i in s:
	if i == '(':
		if a < 0:
			ans += 1
		a += 1
	else:
		a -= 1
		if a < 0:
			ans += 1
if not a:
	print(ans)
else:
	print(-1)


import sys
input = sys.stdin.readline
LI = lambda : list(map(int, input().split()))
MI = lambda : map(int, input().split())
SI = lambda : input().strip('\n')
II = lambda : int(input())
n = II()
s = SI()
if s.count('(') != s.count(')'):
	print(-1)
	exit()
(ans, c1, c2, l) = (0, 0, 0, 0)
stack = []
for (r, c) in enumerate(s):
	if c == '(':
		c1 += 1
	else:
		c2 += 1
	if stack and stack[-1] == '(' and (c == ')'):
		stack.pop()
	else:
		stack.append(c)
	if c1 == c2:
		if stack:
			ans += r - l + 1
		stack.clear()
		(c1, c2) = (0, 0)
		l = r + 1
print(ans)


import re
import sys
exit = sys.exit
from bisect import bisect_left as bsl, bisect_right as bsr
from collections import Counter, defaultdict as ddict, deque
from functools import lru_cache
cache = lru_cache(None)
from heapq import *
from itertools import *
from math import inf
from pprint import pprint as pp
enum = enumerate
ri = lambda : int(rln())
ris = lambda : list(map(int, rfs()))
rln = sys.stdin.readline
rl = lambda : rln().rstrip('\n')
rfs = lambda : rln().split()
cat = ''.join
catn = '\n'.join
mod = 1000000007
d4 = [(0, -1), (1, 0), (0, 1), (-1, 0)]
d8 = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]

def solve():
	n = ri()
	s = rl()
	if n % 2:
		return -1
	ans = bal = k = 0
	for c in s:
		if bal == 0:
			k = 0
		if c == '(':
			bal += 1
		else:
			bal -= 1
			if bal < 0:
				k = 1
		ans += k
	if bal != 0:
		return -1
	return ans
print(solve())


N = int(input())
S = input()
cnt = 0
l = 0
for s in S:
	if s == '(':
		if l == -1:
			cnt += 1
		l += 1
	else:
		l -= 1
	if l < 0:
		cnt += 1
if l == 0:
	print(cnt)
else:
	print(-1)


n = int(input())
s = input()
balance = [0 for i in range(n)]
for i in range(n):
	if i == 0:
		if s[i] == ')':
			balance[i] = -1
		else:
			balance[i] = 1
	elif s[i] == ')':
		balance[i] = balance[i - 1] - 1
	else:
		balance[i] = balance[i - 1] + 1
if balance[-1] != 0:
	print(-1)
else:
	ans = 0
	balance = [0] + balance
	prev_zero = -1
	for i in range(n + 1):
		if balance[i] == 0:
			if prev_zero != -1:
				ans += i - prev_zero
				prev_zero = -1
			if i + 1 < n + 1 and balance[i + 1] < 0:
				prev_zero = i
	print(ans)


n = int(input())
s = input()
a = 0
b = 0
ans = 0
c = 0
for i in range(n):
	if s[i] == '(':
		a = a + 1
	else:
		b = b + 1
	if c == 0:
		if b > a:
			d = i
			c = 1
	elif a == b:
		ans = ans + i - d + 1
		c = 0
if a == b:
	print(ans)
else:
	print(-1)


n = int(input())
s = input()

def f(s):
	if s.count('(') != s.count(')'):
		return -1
	cnt = 0
	res = 0
	flag = False
	for c in s:
		if c == '(':
			cnt += 1
		else:
			cnt -= 1
		if cnt < 0:
			flag = True
		elif cnt > 0:
			flag = False
		if flag:
			res += 1
	return res
print(f(s))


def valid(s, l, h):
	st = 0
	for i in range(l, h + 1):
		if s[i] == '(':
			st += 1
		else:
			if st == 0:
				return False
			st -= 1
	if st == 0:
		return True
	return False
n = int(input())
s = input()
t = 0
x = []
for i in range(n):
	if s[i] == '(':
		t += 1
	else:
		t -= 1
	if t == 0:
		x.append(i)
if t != 0:
	print(-1)
else:
	ans = 0
	if not valid(s, 0, x[0]):
		ans += x[0] + 1
	for i in range(1, len(x)):
		if not valid(s, x[i - 1] + 1, x[i]):
			ans += x[i] - x[i - 1]
	print(ans)


import math
q = 1
for _ in range(q):
	n = int(input())
	s = list(input())
	open = 0
	close = 0
	ans = 0
	k = 0
	flag = 0
	aopen = 0
	aclose = 0
	for i in range(n):
		if s[i] == '(':
			open += 1
			aopen += 1
			if flag == 1 and close >= open:
				k += 1
		else:
			close += 1
			aclose += 1
			if close == open:
				flag = 0
				ans += k
				k = 0
				close = 0
				open = 0
			elif close < open:
				continue
			else:
				flag = 1
				k += 1
	ans += k
	if aopen != aclose:
		print(-1)
	else:
		print(ans)


def check(s):
	l = []
	for i in range(len(s)):
		if s[i] == '(':
			l.append(s[i])
		elif len(l) == 0:
			return len(s)
		else:
			l.pop()
	return 0 if len(l) == 0 else len(s)
n = int(input())
s = input()
(c, o) = (0, 0)
l = []
if s.count('(') != s.count(')'):
	print(-1)
else:
	for i in range(len(s)):
		if s[i] == '(':
			o += 1
		else:
			c += 1
		if o == c:
			l.append(i)
	start = 0
	cnt = 0
	for i in l:
		cnt += check(s[start:i + 1])
		start = i + 1
	print(cnt)


n = int(input())
s = input()
(cnt, f) = (0, True)
(o, c) = (0, 0)
ans = 0
for i in s:
	if i == '(':
		cnt = cnt + 1
		o = o + 1
	else:
		cnt = cnt - 1
		c = c + 1
	if cnt < 0:
		f = False
	if not f:
		ans = ans + 1
	if cnt >= 0:
		f = True
if o == c:
	print(ans)
else:
	print(-1)


from sys import stdin, gettrace
if not gettrace():

	def input():
		return next(stdin)[:-1]

def main():
	n = int(input())
	ss = input()
	depth = 0
	res = 0
	for s in ss:
		ldepth = depth
		if s == '(':
			depth += 1
		else:
			depth -= 1
		if depth < 0 or ldepth < 0:
			res += 1
	if depth != 0:
		print(-1)
	else:
		print(res)
main()


t = int(input())
s = input()
if s.count(')') != s.count('('):
	print(-1)
	exit()
total = 0
val = 0
for c in s:
	needToAdd = val < 0
	if c == ')':
		val -= 1
	else:
		val += 1
	if val < 0 or needToAdd:
		total += 1
print(total)


n = int(input())
z = input()
pravych = 0
lavych = 0
for i in range(n):
	if z[i] == ')':
		pravych += 1
	else:
		lavych += 1

def najdi_usek_viac_lavych(index):
	pp = 0
	ll = 0
	for i in range(index, n):
		if z[i] == ')':
			pp = pp + 1
		else:
			ll = ll + 1
		if ll > pp:
			return i - index

def prehadzuj(z, n, spolu):
	p = 0
	l = 0
	i = 0
	while i < n:
		if z[i] == ')':
			p = p + 1
		else:
			l = l + 1
		if l < p:
			out = najdi_usek_viac_lavych(i + 1)
			spolu = spolu + out + 2
			i = i + 2 + out
			p = 0
			l = 0
		else:
			i = i + 1
	return spolu
if n % 2 == 1:
	print(-1)
elif pravych != lavych:
	print(-1)
else:
	print(prehadzuj(z, n, 0))


import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict

def solution(n, brac):
	if n & 1 == 1:
		print(-1)
		return
	(sums, res) = (0, 0)
	for c in brac:
		if c == '(':
			sums += 1
		if c == ')':
			sums -= 1
		if sums < 0:
			res += 1
		if sums == -1 and c == ')':
			res += 1
	if sums:
		print(-1)
		return
	print(res)
n = int(input())
brac = input()
solution(n, list(brac))


import sys
import os
import time
import collections
from collections import Counter, deque
import itertools
import math
import timeit
import random
from io import BytesIO, IOBase
from bisect import bisect_left as bl
from bisect import bisect_right as br

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=1):
	divisors = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				divisors.append(i)
			else:
				divisors.extend([i, n // i])
	return divisors

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def flin(d, x, default=-1):
	left = right = -1
	for i in range(len(d)):
		if d[i] == x:
			if left == -1:
				left = i
			right = i
	if left == -1:
		return (default, default)
	else:
		return (left, right)

def modpow(b, p, m):
	res = 1
	b = b % m
	while p:
		if p & 1:
			res = res * b % m
		b = b * b % m
		p >>= 1
	return res

def mod_inv(a, m):
	return modpow(a, m - 2, m)

def ncr(n, r, m):
	res = 1
	if r == 0:
		return 1
	if n - r < r:
		r = n - r
	(p, k) = (1, 1)
	while r:
		res = res % m * (n % m * mod_inv(r, m) % m) % m
		n -= 1
		r -= 1
	return res

def ncrlis(n, r, m, fact):
	return fact[n] * (mod_inv(fact[r], m) * mod_inv(fact[n - r], m)) % m % m

def ceil(n, k):
	return n // k + (n % k != 0)

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return list(map(int, input().split()))

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def prr(a, sep=' '):
	print(sep.join(map(str, a)))

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
n = ii()
s = input()
stk = ['$']
(o, c) = (0, 0)
res = 0
for i in range(n):
	if s[i] == '(':
		o += 1
	else:
		c += 1
	if stk[-1] == '(' and s[i] == ')':
		stk.pop()
	else:
		stk.append(s[i])
	if o == c:
		if len(stk) != 1:
			res += o + c
		stk = ['$']
		(o, c) = (0, 0)
if o == c:
	print(res)
else:
	print(-1)


n = int(input())
s = str(input())
k = 0
pr = 0
sc = 0
scp = 0
for i in range(n):
	if s[i] == ')':
		k -= 1
		pr = -1
	else:
		k += 1
		pr = 1
	scp += 1
	if k == 0:
		if pr == 1:
			sc += scp
		scp = 0
if k == 0:
	print(sc)
else:
	print(-1)


n = int(input())
s = input()
cnt = 0
for i in range(n):
	cnt += s[i] == '('
	cnt -= s[i] == ')'
if cnt != 0:
	print(-1)
else:
	fl = 0
	cnt = 0
	ind = 0
	res = 0
	for i in range(n):
		cnt += s[i] == '('
		cnt -= s[i] == ')'
		if cnt < 0:
			fl = 1
		elif cnt == 0 and fl == 0:
			ind = i + 1
		elif cnt == 0 and fl == 1:
			fl = 0
			res += i - ind + 1
			ind = i + 1
	print(res)


x = input()
string = input()
opened = 0
closed = 0
operations = 0
for c in string:
	if c == '(':
		opened += 1
	else:
		closed += 1
		if closed > opened:
			operations += 1
if opened != closed:
	print(-1)
else:
	print(operations * 2)


import sys
input = sys.stdin.readline

def main():
	N = int(input())
	S = input().strip()
	x = S.count('(')
	y = S.count(')')
	if x != y:
		print(-1)
		return
	score = 0
	ans = 0
	cnt = 0
	for s in S:
		cnt += 1
		if s == ')':
			if score - 1 == 0:
				cnt = 0
			score -= 1
		else:
			if score + 1 == 0:
				ans += cnt
				cnt = 0
			score += 1
	print(ans)
main()


from sys import stdin, stdout
n = int(input())
s = input()
if n % 2 != 0:
	print(-1)
else:
	d1 = s.count('(')
	d2 = n - d1
	if d1 != d2:
		print(-1)
	else:
		c1 = 0
		d1 = 0
		r = 0
		i = 0
		reo = False
		while i < n:
			if s[i] == '(':
				c1 += 1
			else:
				d1 += 1
			while d1 > c1:
				if not reo:
					r += 1
					reo = True
				r += 1
				i += 1
				if s[i] == '(':
					c1 += 1
				else:
					d1 += 1
			reo = False
			i += 1
		print(r)


def check(str):
	l = ['$']
	for i in str:
		if l[-1] == '(' and i == ')':
			l.pop()
		else:
			l.append(i)
	if l.pop() != '$':
		return False
	return True
n = int(input())
s = input()
ans = 0
op = 0
cl = 0
if n % 2 != 0:
	print(-1)
else:
	ops = []
	for i in s:
		if i == '(':
			op += 1
		else:
			op -= 1
		ops.append(op)
	if op != 0:
		print(-1)
	else:
		last = 0
		ans = 0
		l = ['$']
		for i in range(len(s)):
			if s[i] == '(':
				op += 1
				l.append(s[i])
			else:
				op -= 1
				if l[-1] == '(':
					l.pop()
				else:
					l.append(')')
			if op == 0:
				if l[-1] == '$':
					l = ['$']
					last = i + 1
					continue
				else:
					ans += i + 1 - last
					last = i + 1
					l = ['$']
		print(ans)


n = int(input())
t = input()
b = 0
a = True
r = 0
for i in range(0, n):
	if t[i] == '(':
		b += 1
	else:
		b -= 1
	if b > 0:
		a = True
	if b < 0:
		a = False
	if a == False:
		r += 1
if b == 0:
	print(r)
else:
	print(-1)


n = int(input())
s = str(input())
count = []
total = 0
for i in s:
	if i == ')':
		total -= 1
	else:
		total += 1
	count.append(total)
if count[-1] != 0:
	print(-1)
else:
	check = False
	start = 0
	out = 0
	for i in range(n):
		if count[i] < 0 and (not check):
			start = i
			check = True
		if count[i] == 0 and check:
			out += i - start + 1
			check = False
	print(out)


input()
arr = map(lambda x: 1 if x == '(' else -1, list(input()))
moves = 0
counter = None
sum = 0
for (i, x) in enumerate(arr):
	sum += x
	if sum < 0 and counter is None:
		counter = i
	if not sum and counter is not None:
		moves += i - counter + 1
		counter = None
if sum:
	print(-1)
else:
	print(moves)


n = int(input())
s = input()
if 2 * s.count('(') != n:
	print(-1)
else:
	i = 0
	ans = 0
	while i < n:
		ln = crct = opn = cls = cur = 0
		j = i
		while j < n:
			if s[j] == '(':
				cur += 1
				crct += 1
				opn += 1
			else:
				if cur > 0:
					cur -= 1
					crct += 1
				cls += 1
			ln += 1
			j += 1
			if opn == cls:
				break
		i = j
		if ln != crct:
			ans += ln
	print(ans)


import sys
input = sys.stdin.readline
from collections import Counter as C
n = int(input())
par = input().rstrip()

def main(n, par):
	check = C(par)
	if check['('] != check[')']:
		return -1
	v = [0] * n
	s = 0
	for (idx, i) in enumerate(par):
		if i == '(':
			s += 1
		else:
			s -= 1
		v[idx] = s
	i = 0
	s = 0
	while i < n:
		if v[i] < 0:
			j = i
			while v[j] < 0:
				j += 1
			s += j - i + 1
			i = j
		i += 1
	return s
print(main(n, par))


n = int(input())
l = input()
if n % 2 != 0:
	print(-1)
else:
	alpha = 0
	count = 0
	for i in l:
		if i == '(':
			alpha += 1
			if alpha <= 0:
				count += 1
		else:
			alpha -= 1
			if alpha < 0:
				count += 1
	print(-1 if alpha != 0 else count)


n = int(input())
s = input()
su = 0
a = []
for x in s:
	if x == '(':
		su += 1
		a.append(su)
	else:
		su -= 1
		a.append(su)
cc = 0
c = 0
if a[n - 1] != 0:
	print(-1)
else:
	for x in range(n):
		if a[x] == 0 and c != 0:
			c += 1
			cc += c
			c = 0
		elif a[x] < 0:
			c += 1
	print(cc)


counter = 0
t = 0
s = int(input())
x = list(input())
for i in range(s):
	if x[i] == '(':
		counter += 1
	else:
		counter += -1
	if counter < 0 or (counter == 0 and x[i] == '('):
		t += 1
if counter == 0:
	print(t)
else:
	print(-1)


import sys
input = sys.stdin.readline
n = int(input())
s = input().rstrip()
if len(s) % 2 == 1:
	print(-1)
else:
	cnt = 0
	for c in s:
		if c == '(':
			cnt += 1
	if cnt != n // 2:
		print(-1)
	else:
		cnt = 0
		sub = 0
		ans = 0
		for c in s:
			if c == '(':
				cnt += 1
				if cnt == 0:
					sub += 1
			else:
				cnt -= 1
			if cnt < 0:
				sub += 1
			elif cnt == 0 and sub > 0:
				ans += sub
				sub = 0
		print(ans)


n = int(input())
t = input()
op = sum((k == '(' for k in t))
if 2 * op != n:
	print(-1)
else:
	sp = 0
	s = 0
	for k in t:
		old = sp
		sp += 2 * (k == '(') - 1
		if sp < 0:
			s += 1
		elif sp == 0 and old < 0:
			s += 1
	print(s)


from collections import Counter
n = int(input())
s = list(input())
c = Counter(s)
ans = 0
mat = 0
if c['('] == c[')']:
	for i in range(n):
		if s[i] == ')' and mat <= 0:
			mat = mat - 1
			ans = ans + 1
		elif s[i] == '(' and mat < 0:
			mat = mat + 1
			ans = ans + 1
		elif s[i] == '(':
			mat = mat + 1
		elif s[i] == ')':
			mat = mat - 1
	print(ans)
else:
	print(-1)


import sys
n = int(sys.stdin.readline())
s = sys.stdin.readline()[:-1]
ans = 0
dif = 0
for i in range(n):
	if s[i] == ')':
		if dif > 0:
			dif -= 1
		elif dif == 0:
			left_limit = i
			dif -= 1
		else:
			dif -= 1
	else:
		dif += 1
		if dif == 0:
			right_limit = i
			ans += right_limit - left_limit + 1
if dif != 0:
	print(-1)
else:
	print(ans)


def solve():
	n = int(input())
	st = input()
	g = 0
	leftbp = -1
	ans = 0
	pos = 0
	for i in st:
		pos += 1
		if i == '(':
			g += 1
			if g == 0:
				ans += pos - leftbp + 1
		else:
			g -= 1
			if g == -1:
				leftbp = pos
	if g != 0:
		print(-1)
	else:
		print(ans)
for i in range(1):
	solve()


from collections import defaultdict
n = int(input())
a = input()
opened = 0
closed = 0
ans = 0
start = -1
if n % 2 == 0:
	for i in range(n):
		if a[i] == '(':
			opened += 1
		else:
			closed += 1
		if closed > opened and start == -1:
			start = i
		elif closed <= opened and start != -1:
			ans += i - start + 1
			start = -1
	if opened == closed:
		print(ans)
	else:
		print('-1')
else:
	print('-1')


n = int(input())
s = input()
r = 0
c = 0
x = 0
for i in range(n):
	if s[i] == ')':
		c -= 1
	else:
		c += 1
	x += 1
	if c == 0 and s[i] == ')':
		x = 0
	if c == 0 and s[i] == '(':
		r += x
		x = 0
if c != 0:
	print(-1)
else:
	print(r)


n = int(input())
A = input()
j = 0
ans = 0
for i in A:
	if i == ')':
		j -= 1
	else:
		j += 1
	if j < 0 or (j == 0 and i == '('):
		ans += 1
print(ans if j == 0 else -1)


n = int(input())
s = str(input())
(o, f) = (0, 0)
for i in range(n):
	if s[i] == '(':
		o += 1
	else:
		f += 1
if o != f:
	print(-1)
	exit()
cml = 0
ans = 0
cnt = 0
for i in range(n):
	if s[i] == '(':
		cml += 1
	else:
		cml -= 1
	if cml < 0:
		cnt += 1
	elif cml == 0 and cnt != 0:
		ans += cnt + 1
		cnt = 0
	else:
		cnt = 0
print(ans)


n = int(input())
s = input()
l = s.count('(')
r = s.count(')')
if l != r:
	print(-1)
else:
	o = 0
	i = 0
	j = 0
	ans = 0
	while i != len(s):
		if s[i] == '(':
			l += 1
		else:
			r += 1
		if r > l:
			o = 1
		if r == l:
			if o == 1:
				ans += i - j + 1
			j = i + 1
			o = 0
			r = 0
			l = 0
		i += 1
	print(ans)


n = int(input())
s = input()
balance = [0 for i in range(n + 1)]
for i in range(1, n + 1):
	if s[i - 1] == '(':
		balance[i] = balance[i - 1] + 1
	else:
		balance[i] = balance[i - 1] - 1
if balance[n] != 0:
	print(-1)
else:
	ans = 0
	i = 0
	while i < n:
		if balance[i] == -1:
			cur = i - 1
			while i < n and balance[i] != 0:
				i += 1
			ans += i - cur
		i += 1
	print(ans)


n = int(input())
seq = input()
count = 0
curc = 1
cost = 0
for i in range(n):
	if seq[i] == ')':
		count = count - 1
	else:
		count += 1
		if count == 0:
			cost = cost + curc
			curc = 1
	if count < 0:
		curc += 1
if count == 0:
	print(cost)
else:
	print(-1)


def Solve(n):
	s = input()
	c = 0
	for ch in s:
		if ch == '(':
			c += 1
		else:
			c -= 1
	if c:
		print(-1)
		return
	ans = 0
	pos = 0
	i = 0
	flag = True
	for ch in s:
		if ch == '(':
			c += 1
		else:
			c -= 1
		if c < 0:
			flag = False
		if not c:
			if flag:
				pos = i + 1
			else:
				flag = True
				ans += i - pos + 1
				pos = i + 1
		i += 1
	print(ans)
Solve(int(input()))


n = int(input())
s = input()
a = []
c = 0
for i in s:
	if i == ')':
		if a and a[-1] == '(':
			_ = a.pop()
		else:
			a.append(i)
	elif a and a[-1] == ')':
		_ = a.pop()
		c += 2
	else:
		a.append(i)
if a:
	print(-1)
else:
	print(c)


def answer(arr):
	if len(arr) % 2 == 1 or arr.count('(') != len(arr) // 2:
		return -1
	ans = 0
	t = 0
	for i in range(0, len(arr)):
		if arr[i] == '(':
			if t == -1:
				ans += 1
			t += 1
		elif arr[i] == ')':
			t -= 1
		if t < 0:
			ans += 1
	return ans
n = int(input())
s = input()
print(answer(s))


n = int(input())
A = input()
j = 0
l = 0
for i in A:
	if i == ')':
		j -= 1
	else:
		j += 1
	if j < 0:
		l += 1
	elif j == 0 and i == '(':
		l += 1
if j == 0:
	print(l)
else:
	print(-1)


def read():
	n = int(input())
	s = input()
	return (n, s)

def solve(n, s):
	total = 0
	c = 0
	last = -1
	for i in range(n):
		if s[i] == ')':
			if c == 0:
				last = i
			c -= 1
		else:
			c += 1
			if c == 0:
				total += i - last + 1
	return -1 if c != 0 else total
result = solve(*read())
print(result)


n = int(input())
s = input()
count = 0
ans = 0
wrong_sequence = False
for i in range(n):
	if s[i] == '(':
		count += 1
	else:
		count -= 1
	if wrong_sequence:
		if count == 0:
			ans += i - prev
			wrong_sequence = False
			prev = i
	if count < 0 and (not wrong_sequence):
		wrong_sequence = True
		prev = i - 1
if count == 0:
	print(ans)
else:
	print('-1')


input()
s = [0]
for i in input():
	s.append(s[-1] + (1 if i == '(' else -1))
ans = [0]
for i in range(1, len(s)):
	if s[i - 1] < 0 and s[i] < 0:
		ans[-1] += 1
	elif s[i] < 0:
		ans.append(2)
print(sum(ans) if s[-1] == 0 else -1)


import sys
import bisect
import heapq
from math import *
from collections import defaultdict as dd
from collections import deque
from collections import Counter as c
from itertools import combinations as comb
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(var):
	sys.stdout.write(var)

def l():
	return list(map(int, data().split()))

def sl():
	return list(map(ele, data().split()))

def sp():
	return map(int, data().split())

def ssp():
	return map(ele, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [[val for i in range(n)] for j in range(m)]
n = int(data())
ele = data()
f = 0
s = 0
ans = 0
for i in range(n):
	if ele[i] == '(':
		s += 1
	elif ele[i] == ')':
		s -= 1
	if s == 0 and f == -1:
		l = i - pos + 1
		ans += l
		f = 0
	if s == -1 and f == 0:
		f = -1
		pos = i
if s == 0 and f == -1:
	l = i - pos + 1
	ans += l
	f = 0
elif s != 0:
	ans = -1
if ans == -1:
	out('-1')
	exit()
print(ans)


import sys
import math
from collections import defaultdict, Counter
n = int(input())
s = input()
c = 0
flag = 0
time = 0
for i in s:
	if i == '(':
		c += 1
	else:
		c -= 1
		if c < 0:
			flag = 1
if c != 0:
	print(-1)
elif flag == 0:
	print(0)
else:
	flag = -1
	c = 0
	c1 = 0
	for i in range(n):
		if s[i] == '(':
			c += 1
		else:
			c1 += 1
		if c1 > c and flag == -1:
			flag = i
		if flag != -1 and c == c1:
			time += i + 1 - flag
			flag = -1
	print(time)


from itertools import accumulate
n = int(input())
s = input()
a = []
for c in s:
	if c == '(':
		a += [+1]
	else:
		a += [-1]
acc = list(accumulate(a))
if acc[-1] != 0:
	print(-1)
	exit()
total = 0
neg_start = -1
for (i, x) in enumerate(acc):
	if x < 0 and neg_start == -1:
		neg_start = i
	if x == 0 and neg_start != -1:
		total += i - neg_start + 1
		neg_start = -1
print(total)


from collections import defaultdict
from queue import deque
from sys import stdin

def read_tuple():
	return map(int, input().split())

def read_int():
	return int(input())

def read_list():
	return list(map(int, input().split()))
n = read_int()
seq = list(input())
(o, c) = (0, 0)
moves = 0
stk = deque()
for i in range(n):
	if seq[i] == '(':
		o += 1
		stk.append('(')
	else:
		c += 1
		if len(stk) > 0 and stk[-1] == '(':
			stk.pop()
		else:
			stk.append(')')
	if len(stk) == 0:
		(o, c) = (0, 0)
	elif o == c:
		moves += o + c
		(o, c) = (0, 0)
		stk.clear()
if o != c:
	print(-1)
else:
	print(moves)


from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
M = mod = 10 ** 9 + 7

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split()]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
n = val()
s = li2()
tot = 0
temp = s.count('(')
if temp != n // 2 or n & 1:
	print(-1)
	exit()
left = right = i = tot = switch = 0
while i < n:
	if s[i] == '(':
		left += 1
	else:
		right += 1
	if right > left and (not switch):
		lastind = i
		switch = 1
	if switch and right == left:
		switch = 0
		tot += i - lastind + 1
	i += 1
print(tot)


input()
s = input()
t = 0
l = 0
e = -1
for i in range(len(s)):
	if s[i] == '(':
		l += 1
		if l == 0:
			t += i - e + 1
	elif s[i] == ')':
		l -= 1
		if l == -1:
			e = i
if l != 0:
	print(-1)
else:
	print(t)


t = int(input())
s = input()
count = 0
ans = 0
for i in s:
	if i == ')':
		count -= 1
	else:
		if count < 0:
			ans += 2
		count += 1
if count == 0:
	print(ans)
else:
	print(-1)


n = int(input())
a = input()
count = 0
time = 0
for element in a:
	if element == '(':
		count += 1
	elif element == ')':
		count -= 1
		if count < 0:
			time += 2
if count != 0:
	print(-1)
else:
	print(time)


t = int(input())
s = input()
count = 0
countA = 0
countB = 0
for i in s:
	if i == '(':
		countA += 1
	else:
		countB += 1
	if countB > countA:
		count += 1
	if countB - 1 == countA and i == ')':
		count += 1
if countA != countB:
	print(-1)
else:
	print(count)


n = int(input())
s = input()
(a, b) = (0, 0)
for chr in s:
	if chr == '(':
		a += 1
	else:
		a -= 1
		if a < 0:
			b += 2
if a != 0:
	b = -1
print(b)


n = int(input())
seq = input()
ans = 0
if n % 2 != 0:
	ans = -1
elif seq.count('(') != n // 2:
	ans = -1
else:
	idx = 0
	while idx < n:
		point = 0
		while point >= 0 and idx < n:
			if seq[idx] == '(':
				point += 1
			else:
				point -= 1
			idx += 1
		if idx >= n:
			break
		start_mod = idx - 1
		while point < 0:
			if seq[idx] == '(':
				point += 1
			else:
				point -= 1
			idx += 1
		ans += idx - start_mod
print(ans)


n = int(input())
s = input()
if s.count('(') != s.count(')'):
	print(-1)
elif n % 2 != 0:
	print(-1)
else:
	prefix = [0]
	for i in range(n):
		if s[i] == '(':
			prefix.append(prefix[-1] + 1)
		else:
			prefix.append(prefix[-1] - 1)
	i = 0
	n = n + 1
	down = 0
	while i < n:
		if prefix[i] < 0:
			down += 2
			i = i + 1
			while i < n and prefix[i] != 0:
				i += 1
				down += 1
		else:
			i += 1
	print(down)


import sys
import math
import heapq
import collections

def inputnum():
	return int(input())

def inputnums():
	return map(int, input().split())

def inputlist():
	return list(map(int, input().split()))

def inputstring():
	return [x for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
n = inputnum()
s = inputstring()
left = 0
right = 0
start = -1
ans = 0
wrong = False
for i in range(n):
	if s[i] == '(':
		left += 1
	else:
		right += 1
	if not wrong and right > left:
		start = i
		wrong = True
	if wrong and left == right:
		ans += i - start + 1
		wrong = False
		start = -1
if left != right:
	print(-1)
else:
	print(ans)


input()
s = input()
acc = 0
time = 0
l = 0
for (i, c) in enumerate(s):
	if c == '(':
		acc += 1
		if acc == 0:
			time += i + 1 - l
	else:
		acc -= 1
		if acc == -1:
			l = i
if acc != 0:
	print(-1)
else:
	print(time)


def findTime(n, s):
	if n % 2 == 1 or s.count('(') != n // 2:
		print('-1')
		return
	else:
		lenS = 0
		c = 0
		prev = 1
		for i in s:
			if i == '(':
				c += 1
			else:
				c -= 1
			if c < 0 or prev < 0:
				lenS += 1
			prev = c
		print(lenS)
n = int(input())
s = input()
findTime(n, s)


n = int(input())
s = input()
(oplist, cllist) = ([], [])
for i in range(n):
	if s[i] == '(':
		oplist.append(i)
	if s[i] == ')':
		cllist.append(i)
if len(oplist) != len(cllist):
	exit(print(-1))
(optr, cptr) = (0, 0)
count = 0
while optr < len(oplist) and cptr < len(cllist):
	if oplist[optr] < cllist[cptr]:
		optr += 1
		cptr += 1
		continue
	count += 1
	optr += 1
	cptr += 1
print(count * 2)


n = int(input())
s = input()
m = {'(': 1, ')': -1}
ans = 0
tmp = 0
count = 0
for c in s:
	tmp += m[c]
	count += 1
	if tmp == 0:
		if m[c] == 1:
			ans += count
			count = 0
		else:
			count = 0
if tmp == 0:
	print(ans)
else:
	print(-1)


n = int(input())
s = str(input())
chk = 0
for i in range(n):
	if s[i] == '(':
		chk += 1
	else:
		chk -= 1
if chk != 0:
	print(-1)
	exit(0)
v = 0
ok = True
ans = 0
so_far = 0
for i in range(n):
	if s[i] == '(':
		v += 1
	else:
		v -= 1
	so_far += 1
	if v == 0:
		if not ok:
			ans += so_far
			ok = True
			so_far = 0
		if ok:
			so_far = 0
	if v < 0:
		ok = False
print(ans)


def check(s):
	st = []
	for i in s:
		if i == '(':
			st.append('(')
		else:
			if len(st) == 0:
				return False
			st.pop()
	else:
		return True
n = int(input())
s = list(input())
if s.count('(') != s.count(')'):
	print(-1)
	exit()
if check(s):
	print(0)
	exit()
c = 0
x = 0
y = 0
for i in range(n):
	if s[i] == '(':
		if x == 0 and y == 0:
			j = i
		x += 1
	else:
		if x == 0 and y == 0:
			j = i
		y += 1
	if x == y:
		if not check(s[j:i + 1]):
			c += x + y
		x = 0
		y = 0
print(c)


import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict, deque, Counter
from bisect import *
from math import sqrt, pi
import math
from itertools import permutations

def main():
	n = int(input())
	s = input().rstrip()
	a = s.count('(')
	if 2 * a != n:
		print(-1)
	else:
		f = []
		b = []
		ans = 0
		for i in range(n):
			if s[i] == '(':
				if b == []:
					f.append(i)
				else:
					b.pop()
					ans += 2
			elif f != []:
				f.pop()
			else:
				b.append(i)
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


a = int(input())
s = list(input())
r = []
l = []
for i in range(a):
	if s[i] == '(':
		r.append(i + 1)
	elif s[i] == ')':
		l.append(i + 1)
if len(r) != len(l):
	print(-1)
else:
	c = 0
	for i in range(len(r)):
		if r[i] > l[i]:
			c += 2
	print(c)


from math import factorial
from collections import Counter, defaultdict
from heapq import heapify, heappop, heappush
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 1000000007
INF = float('inf')

def main():
	n = N()
	s = list(input())
	(l, r) = (0, 0)
	res = 0
	tag = True
	for i in range(n):
		if r > l:
			tag = False
		if s[i] == '(':
			l += 1
		elif s[i] == ')':
			r += 1
		if l == r:
			if tag == False:
				res += l + r
			l = 0
			r = 0
			tag = True
	if l == r:
		print(res)
	else:
		print(-1)
main()


n = int(input(''))
s = input('')
l = 0
a = 0
b = 0
d = 0
if n % 2 != 0:
	print('-1')
else:
	for i in range(0, len(s)):
		if s[i] == '(':
			a = a + 1
			d = 1
		else:
			b = b + 1
			d = 0
		if b == a and d == 1:
			l += 1
		elif b > a:
			l = l + 1
	if a != b:
		print('-1')
	else:
		print(l)


n = int(input())
s = input()
bal = 0
ans = 0
i = 0
while i < len(s):
	if s[i] == '(':
		bal = bal + 1
	else:
		bal = bal - 1
		if bal < 0:
			ans = ans + 1
	i = i + 1
if bal == 0:
	print(2 * ans)
else:
	print(-1)


from __future__ import division, print_function
import sys
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
	input = raw_input
import os, sys, bisect, copy
from collections import defaultdict, Counter, deque
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
if os.path.exists('out.txt'):
	sys.stdout = open('out.txt', 'w')

def input():
	return sys.stdin.readline()

def mapi(arg=0):
	return map(int if arg == 0 else str, input().split())
n = int(input())
a = input().strip()
if a.count('(') != a.count(')'):
	print(-1)
	exit(0)
bal = 0
cnt = 0
res = 0
for (i, v) in enumerate(a):
	bal += (v == '(') - (v == ')')
	if bal < 0:
		cnt += 1
	elif cnt:
		res += cnt + 1
		cnt = 0
print(res)


n = int(input())
s = input()
flag = 0
open = 0
close = 0
for i in range(len(s)):
	if s[i] == '(':
		open += 1
	else:
		close += 1
sum = 0
if open == close:
	open = 0
	close = 0
	for i in range(len(s)):
		if s[i] == ')':
			if flag == 0 and open == 0:
				j = i
				flag = 1
			if flag == 1:
				close += 1
			else:
				open -= 1
		elif s[i] == '(':
			if flag == 1:
				close -= 1
				if close == 0:
					sum += i - j + 1
					flag = 0
			else:
				open += 1
	print(sum)
else:
	print('-1')


n = int(input())
s = str(input())
(x, y, ans, z) = (int(0), int(0), int(0), int(0))
for i in s:
	if i == '(':
		x += 1
		z += 1
	else:
		y += 1
		if z > 0:
			z -= 1
	if x == y:
		if z != 0:
			ans += x + y
		(x, y, z) = (0, 0, 0)
if x != y:
	print(-1)
else:
	print(ans)


n = int(input())
s = input()
if s.count('(') != s.count(')'):
	print('-1')
else:
	r = 0
	count = 0
	start = 0
	end = 0
	for i in range(n):
		if r > 0:
			start = i
		elif r == 0:
			if s[i] == ')':
				start = i
			else:
				start = i
		elif r == -1 and s[i] == '(':
			end = i
			count += end - start + 1
		if s[i] == '(':
			r += 1
		else:
			r -= 1
	print(count)


n = int(input())
seq = input()
(cl, op) = (0, 0)
i = 0
ns = 0
while i < n:
	if seq[i] == ')':
		if op > 0:
			op = op - 1
		else:
			cl = cl + 1
			ns = ns + 1
	elif cl > 0:
		cl = cl - 1
		ns = ns + 1
	else:
		op = op + 1
	i = i + 1
if op != 0 or cl != 0:
	print(-1)
else:
	print(ns)


n = int(input())
s = input()
sm = 0
ans = 0
if len(s) % 2 != 0:
	print(-1)
else:
	for i in s:
		if s == '(':
			sm += 1
		else:
			sm -= 1
	if sm == 0:
		print(-1)
	else:
		flag = False
		val = 0
		l = 0
		for i in range(n):
			if s[i] == '(':
				val += 1
				if val <= 0:
					l += 1
				if val == 0:
					ans += l
					l = 0
			elif val > 0:
				val -= 1
			else:
				l += 1
				val -= 1
		if val == 0:
			print(ans)
		else:
			print(-1)


n = int(input())
s = str(input())
maincount = 0
count = 0
length = 0
count1 = 0
for i in range(len(s)):
	if s[i] == ')':
		if count1 == 0:
			count += 1
			length += 1
		else:
			count1 -= 1
	if s[i] == '(':
		if count > 0:
			count -= 1
			length += 1
			if count == 0:
				maincount += length
				length = 0
		else:
			count1 += 1
if count != 0 or count1 != 0:
	print(-1)
else:
	print(maincount)


n = int(input())
s = input()
pre = 0
cnt = 0
l = 0
r = 0
ans = 0
for i in range(n):
	if s[i] == '(':
		cnt += 1
	else:
		cnt -= 1
	if cnt < 0:
		if pre >= 0:
			r = i
			l = r - 1
		else:
			r = i
	if cnt >= 0:
		if pre < 0:
			r = i
			ans += r - l
		l = r = i
	pre = cnt
if cnt != 0:
	print(-1)
	exit()
print(ans)


from math import *

def binarySearch(arr, x, i):
	l = i
	r = len(arr) - 1
	while l <= r:
		mid = (l + r) // 2
		if arr[mid] == x:
			return mid
		elif arr[mid] < x:
			l = mid + 1
		else:
			r = mid - 1
	return -1

def js(arr, x):
	l = 0
	r = len(arr) - 1
	ans = -1
	while l <= r:
		m = (l + r) // 2
		if arr[m] <= x:
			ans = m
			l = m + 1
		else:
			r = m - 1
	return ans

def jg(arr, x):
	l = 0
	r = len(arr) - 1
	ans = -1
	while l <= r:
		m = (l + r) // 2
		if arr[m] >= x:
			ans = m
			r = m - 1
		else:
			l = m + 1
	return ans
from collections import deque
n = int(input())
s = input()
ans = 0
if s.count('(') != s.count(')'):
	print(-1)
else:
	st = deque()
	t1 = 0
	t2 = 0
	ss = deque()
	for i in range(n):
		if s[i] == '(':
			st.append('(')
			ss.append(i)
			t1 += 1
			if t1 == t2:
				st = deque()
				ans += i - ss[0] + 1
				ss = deque()
		else:
			t2 += 1
			if len(st) > 0:
				if st[-1] == '(':
					st.pop()
					ss.pop()
					t1 -= 1
					t2 -= 1
				elif t1 == t2:
					st = deque()
					ans += i - ss[0] + 1
					ss = deque()
				else:
					ss.append(i)
			else:
				ss.append(i)
	print(ans)


from sys import stdin
from math import ceil
inp = lambda : stdin.readline().strip()
n = int(inp())
s = inp()
if s.count('(') != s.count(')'):
	print(-1)
else:
	opens = 0
	closes = 0
	ans = 0
	for i in range(n):
		if s[i] == '(':
			opens += 1
		else:
			closes += 1
			if opens - closes < 0:
				ans += 1
	print(ans * 2)


n = int(input())
s = input()
if s.count('(') != s.count(')'):
	print(-1)
	exit()
v = [0]
for i in s:
	if i == '(':
		v.append(v[-1] + 1)
	if i == ')':
		v.append(v[-1] - 1)
c = 0
i = 0
while i < len(v):
	if v[i] < 0:
		while True:
			c += 1
			if v[i] == 0:
				break
			i += 1
	i += 1
print(c)


from collections import Counter
n = int(input())
s = input()
a = list(Counter(s).values())
if len(a) != 2 or len(set(a)) != 1:
	print(-1)
else:
	ans = []
	for i in range(len(s)):
		if s[i] == '(':
			ans.append(1)
		else:
			ans.append(-1)
	fina = []
	for i in range(len(ans)):
		if i == 0:
			fina.append(ans[i])
		else:
			fina.append(fina[-1] + ans[i])
	maxans = []
	count = 0
	for i in range(len(fina)):
		if fina[i] < 0:
			count += 1
		elif fina[i] == 0:
			if count == 0:
				maxans.append(0)
			else:
				maxans.append(count + 1)
				count = 0
	print(sum(maxans))


n = int(input())
s = input()
t = []
for i in range(n):
	if s[i] == '(':
		t.append(1)
	else:
		t.append(-1)
u = [t[0]]
for i in range(1, n):
	u.append(u[-1] + t[i])
if u[-1] != 0:
	print(-1)
	exit()
ans = 0
for i in range(n):
	if u[i] < 0:
		ans += 1
	elif u[i] == 0:
		if u[i - 1] < 0:
			ans += 1
print(ans)


n = int(input())
S = input()
stack = []
r = 0
l = 0
ans = 0
for i in range(n):
	if len(stack) == 0:
		if S[i] == ')':
			l += 1
		else:
			r += 1
		stack.append(S[i])
	elif S[i] == ')' and stack[len(stack) - 1] != S[i]:
		stack.pop()
		if len(stack) == 0:
			l = 0
			r = 0
		else:
			l += 1
	else:
		stack.append(S[i])
		if S[i] == ')':
			l += 1
		else:
			r += 1
	if r == l:
		ans += r + l
		stack = []
		r = 0
		l = 0
if len(stack) == 0:
	print(ans)
else:
	print(-1)


a = int(input())
b = input()
op = b.count('(')
cl = a - op
if op != cl:
	print(-1)
else:
	closrn = 0
	oprn = 0
	flag = 0
	tot = 0
	for i in range(a):
		if b[i] == '(':
			oprn = oprn + 1
		else:
			closrn = closrn + 1
		if closrn > oprn and flag != 1:
			start = i
			flag = 1
		if flag == 1 and closrn == oprn:
			tot = tot + i - start + 1
			flag = 0
	print(tot)


from math import ceil, sqrt, gcd, log, floor
from collections import deque

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().strip().split(' '))

def li():
	return list(mi())

def msi():
	return map(str, input().strip().split(' '))

def lsi():
	return list(msi())
n = ii()
s = si()
ans = 0
c = 0
prev = 0
q = []
for i in range(n):
	if s[i] == ')':
		if len(q) != 0:
			if q[len(q) - 1] == '(':
				q.pop()
			else:
				q.append(')')
		else:
			q.append(')')
	elif len(q) != 0:
		if q[len(q) - 1] == '(':
			q.append('(')
		else:
			q.pop()
			ans += 2
	else:
		q.append('(')
if len(q):
	print('-1')
else:
	print(ans)


from sys import stdin, stdout
from math import sqrt
get = stdin.readline
put = stdout.write
n = int(get())
a = input()
p = t = 0
for i in a:
	if i == '(':
		t += 1
	else:
		t -= 1
		if t < 0:
			p += 2
if t != 0:
	exit(print('-1'))
put(str(p))


n = int(input())
S = input().strip()
l = r = 0
cc = 0
xx = 0
for c in S:
	if c == '(':
		cc += 1
	else:
		cc -= 1
	if cc < 0:
		xx += 1
	if cc == 0 and xx:
		r += xx + 1
		xx = 0
if cc != 0:
	print(-1)
else:
	print(r)


n = int(input())
s = input()
(cls, opn) = (0, 0)
(cf, ol) = (-1, 0)
ans = 0
(st1, st2) = ([], [])
for i in range(n):
	if s[i] == '(':
		st1.append('(')
		opn += 1
		ol = i
		if opn == cls and cf != -1:
			ans += ol - cf + 1
			cf = -1
			st1 = []
	elif len(st1) > 0 and st1[-1] == '(':
		st1.pop()
		opn -= 1
	else:
		st1.append(')')
		cls += 1
		if cf == -1:
			cf = i
if len(st1) > 0:
	print(-1)
else:
	print(ans)


def main():
	n = int(input())
	s = input()
	if n % 2:
		print(-1)
		return
	mi = 0
	cnt = 0
	ans = 0
	last = 0
	o = 0
	c = 0
	for (idx, i) in enumerate(s):
		if i == '(':
			cnt += 1
			o += 1
		else:
			cnt -= 1
			c += 1
			mi = min(mi, cnt)
		if cnt == 0:
			if mi < 0:
				ans += idx - last + 1
			last = idx + 1
			mi = 0
	if o != c:
		print(-1)
	else:
		print(ans)
	return
main()


n = int(input())
s = input()
stack = []
stack2 = []
pair = 0
if s.count(')') != s.count('('):
	print(-1)
else:
	for i in s:
		if i == '(':
			stack2.append(i)
		if i == ')':
			if stack2:
				del stack2[-1]
			else:
				stack.append(i)
		elif stack and i == '(':
			del stack[-1]
			del stack2[-1]
			pair += 2
	print(pair)


import sys
import os
import time
import collections
from collections import Counter, deque
import itertools
import math
import timeit
import random
import string

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=1):
	divisors = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				divisors.append(i)
			else:
				divisors.extend([i, n // i])
	return divisors

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def flin(d, x, default=-1):
	left = right = -1
	for i in range(len(d)):
		if d[i] == x:
			if left == -1:
				left = i
			right = i
	if left == -1:
		return (default, default)
	else:
		return (left, right)

def ceil(n, k):
	return n // k + (n % k != 0)

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return list(map(int, input().split()))

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def prr(a, sep=' '):
	print(sep.join(map(str, a)))

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)
n = ii()
s = [x for x in input()]
o = s.count('(')
c = n - o
if o != c:
	exit(print(-1))
o = c = 0
good = 1
res = 0
prev = -1
for i in range(n):
	if s[i] == '(':
		o += 1
	else:
		c += 1
	if c > o:
		good = 0
	if c == o:
		if not good:
			res += i - prev
		o = c = 0
		prev = i
		good = 1
print(res)


n = int(input())
st = input()
val = []
for i in st:
	if i == '(':
		val.append(1)
	else:
		val.append(-1)
for i in range(n - 1):
	val[i + 1] += val[i]
look = False
ans = 0
count = 0
for i in range(n):
	if val[i] == 0:
		count += 1
		if look:
			ans += count
			look = False
			count = 0
		else:
			count = 0
	if val[i] < 0:
		look = True
		count += 1
	if val[i] > 0:
		count += 1
if val[-1] == 0:
	print(ans)
else:
	print(-1)


n = int(input())
s = input()
op = 0
cl = 0
br = []
st = True
for i in range(n):
	if s[i] == '(':
		op += 1
	elif s[i] == ')':
		if op > 0:
			op -= 1
		else:
			cl += 1
	br.append((op, cl))
pos = -1
st = 0
tp = False
for i in range(n - 1, -1, -1):
	if br[i][0] == 0 and br[i][1] == 0:
		pos = i
ans = 0
prev = 0
op = 0
cl = 0
b = False
if br[n - 1][0] != br[n - 1][1]:
	print('-1')
	b = True
for i in range(pos + 1, n):
	if s[i] == '(':
		op += 1
	elif s[i] == ')':
		if op > 0:
			op -= 1
		else:
			cl += 1
	if tp == False:
		st = op
		prev = i
		tp = True
	if op == cl:
		if st < op:
			ans += i - prev + 1
		tp = False
if b == False:
	print(ans)


n = int(input())
s = input()
left = 0
right = 0
ns = 0
fl = False
for i in s:
	if i == '(':
		left += 1
	else:
		right += 1
	if left < right:
		ns += 1
		fl = True
	elif left == right and fl:
		ns += 1
		fl = False
if left == right:
	print(ns)
else:
	print(-1)


import time

def solve(size, string):
	math_repr = get_mah_repr(string)
	if len(math_repr) == 0:
		return -1
	else:
		return find_possible(size, math_repr)

def find_possible(size, brackets):
	moves = 0
	temp_start = 0
	temp_sum = 0
	for i in range(size):
		temp_sum += brackets[i]
		if temp_sum == (i + 1 - temp_start) / 2:
			moves += count_moves(brackets[temp_start:i + 1 if i + 1 < size else size])
			temp_sum = 0
			temp_start = i + 1 if i + 1 < size else size - 1
	return moves

def get_mah_repr(string):
	open_bracket = 0
	close_bracket = 0
	math_repr = []
	for bracket in string:
		if bracket == '(':
			math_repr.append(0)
			open_bracket += 1
		else:
			math_repr.append(1)
			close_bracket += 1
	if close_bracket != open_bracket:
		return []
	else:
		return math_repr

def count_moves(sub_seq):
	if check_right(sub_seq):
		return 0
	else:
		return len(sub_seq)

def check_right(seq):
	open_b = 0
	for b in seq:
		if b == '(':
			open_b += 1
		elif open_b > 0:
			open_b -= 1
	return open_b == 0

def solve_2(size, string):
	open_bracket = 0
	close_bracket = 0
	moves = 0
	temp_start = 0
	temp_sum = 0
	for i in range(len(string)):
		if string[i] == '(':
			open_bracket += 1
		else:
			close_bracket += 1
		temp_sum += 0 if string[i] == '(' else 1
		if temp_sum == (i + 1 - temp_start) / 2:
			moves += count_moves(string[temp_start:i + 1 if i + 1 < size else size])
			temp_sum = 0
			temp_start = i + 1 if i + 1 < size else size - 1
	if close_bracket != open_bracket:
		return -1
	else:
		return moves
str_len = int(input())
line = input()
print(solve_2(str_len, line))


n = int(input())
string = input()
stack = []
lenstack = 0
start = string.count('(')
end = string.count(')')
if start != end:
	print(-1)
else:
	reorder = 0
	stack = []
	for i in string:
		if lenstack == 0:
			stack.append(i)
			lenstack += 1
		elif i == '(':
			if stack[-1] == ')':
				reorder += 2
				lenstack -= 1
				stack.pop()
			else:
				lenstack += 1
				stack.append(i)
		elif stack[-1] == '(':
			stack.pop()
			lenstack -= 1
		else:
			lenstack += 1
			stack.append(i)
	print(reorder)


n = int(input())
s = input()
pre = [0] * n
(c1, c2) = (0, 0)
if s[0] == '(':
	pre[0] += 1
	c1 += 1
else:
	pre[0] -= 1
	c2 += 1
if pre[0] < 0:
	fl = True
else:
	fl = False
prev = 0
ans = 0
for i in range(1, n):
	if s[i] == '(':
		pre[i] = pre[i - 1] + 1
		c1 += 1
	else:
		pre[i] = pre[i - 1] - 1
		c2 += 1
	if pre[i] == 0 and fl:
		ans += i - prev + 1
		fl = False
	if pre[i] < 0 and (not fl):
		prev = i
		fl = True
if c1 != c2:
	print(-1)
else:
	print(ans)


n = int(input())
arr = input()
if n % 2 == 1:
	print(-1)
else:
	if arr[0] == '(':
		last = 1
		b = [1]
	else:
		last = -1
		b = [-1]
	for i in range(len(arr) - 1):
		if arr[i + 1] == '(':
			last += 1
			b.append(last)
		else:
			last -= 1
			b.append(last)
	if last != 0:
		print(-1)
	elif min(b) > -1:
		print(0)
	else:
		ans = 0
		tbd = 0
		for i in range(n):
			if 0 > b[i] and tbd == 0:
				tbd = 1
				l = 1
			elif 0 > b[i] and tbd == 1:
				l += 1
			elif b[i] == 0 and tbd == 1:
				tbd = 0
				ans += l + 1
				l = 0
		print(ans)


import sys
n = int(input())
s = sys.stdin.readline().strip()
cumsum = [0] * (n + 1)
for i in range(1, n + 1):
	if s[i - 1] == '(':
		cumsum[i] = cumsum[i - 1] + 1
	else:
		cumsum[i] = cumsum[i - 1] - 1
if cumsum[n] != 0:
	print(-1)
else:
	ans = 0
	i = 1
	while i <= n:
		if cumsum[i] < 0:
			j = i
			while j <= n and cumsum[j] <= 0:
				j += 1
				ans += 1
			i = j
		else:
			i += 1
	print(ans)


def abhi(t):
	cur = 0
	ans = 0
	temp = 0
	st = 999999999999999
	for j in range(n):
		if t[j] == '(':
			cur += 1
		else:
			cur -= 1
		if cur < 0:
			st = min(st, j)
			temp = 1
		if cur == 0:
			if temp == 1:
				ans += j - st + 1
				temp = 0
				st = 999999999999999
	return ans
n = int(input())
t = list(input())
a = 0
b = 0
for j in t:
	if j == '(':
		a += 1
	else:
		b += 1
if a != b:
	print(-1)
else:
	print(abhi(t))


from sys import stdin, stdout

def main():
	n = int(stdin.readline().strip())
	s = stdin.readline().strip()
	stack1 = []
	trigger = False
	(o_c, c_c, op) = (0, 0, 0)
	for i in range(n):
		if s[i] == '(':
			if trigger:
				o_c += 1
			else:
				stack1.append(i)
		elif not stack1:
			trigger = True
			c_c += 1
		else:
			stack1.pop()
		if trigger and c_c == o_c:
			op += c_c * 2
			c_c = 0
			o_c = 0
			trigger = False
	if not stack1 and (not trigger):
		stdout.write(f'{op}')
	else:
		stdout.write('-1')
main()


def solve():
	n = int(input())
	s = input()
	if s.count('(') != s.count(')'):
		print(-1)
		exit(0)
	res = []
	k = 0
	res.append(k)
	for i in range(n):
		if s[i] == '(':
			k += 1
		else:
			k -= 1
		res.append(k)
	k = 0
	temp = 0
	for i in range(n + 1):
		if res[i] <= 0:
			temp += 1
		else:
			k += max(temp - 1, 0)
			temp = 0
	k += max(temp - 1, 0)
	print(k)
solve()


n = int(input())
st = input()
c = 0
t = 0
for i in st:
	if i == '(':
		c += 1
	else:
		c -= 1
		if c < 0:
			t += 2
if c == 0:
	print(t)
else:
	print('-1')


n = int(input())
a = list(input())
ar = [1 if k == '(' else -1 for k in a]
ans = 0
for k in range(1, n):
	ar[k] += ar[k - 1]
flag = False
temp = -1
for k in range(n):
	if ar[k] < 0:
		flag = True
	if ar[k] == 0 and flag:
		ans += k - temp
		temp = k
		flag = False
	elif ar[k] == 0:
		temp = k
if ar[-1] != 0:
	print(-1)
else:
	print(ans)


n = int(input())
s = input()
(cost, cur, ind) = (0, 0, -1)
for i in range(n):
	prev = cur
	cur += 1 if s[i] == '(' else -1
	if cur == 0:
		if prev < 0:
			cost += i - ind
		ind = i
print(-1 if cur else cost)


n = int(input())
s = input()
if n & 1 or s.count('(') != s.count(')'):
	print(-1)
	exit()
d = 0
length = 0
total = 0
unmatched = False
for i in s:
	length += 1
	if i == ')' and d == 0 and (not unmatched):
		length = 1
		d -= 1
		unmatched = True
	elif i == '(':
		d += 1
	elif i == ')':
		d -= 1
	if d == 0 and unmatched:
		total += length
		length = 0
		unmatched = False
print(total)


import sys
n = int(sys.stdin.readline())
arr = list(sys.stdin.readline().rstrip())
if n % 2 == 1:
	print(-1)
else:
	o = 0
	c = 0
	for i in arr:
		if i == '(':
			o += 1
		else:
			c += 1
	if o != c:
		print(-1)
	else:
		temp = [0] * (n + 1)
		if arr[0] == '(':
			temp[1] = 1
		else:
			temp[1] = -1
		for i in range(2, n + 1):
			if arr[i - 1] == '(':
				temp[i] = temp[i - 1] + 1
			else:
				temp[i] = temp[i - 1] - 1
		ans = 0
		for i in range(n):
			if temp[i] < 0 and temp[i + 1] <= 0 or (temp[i] <= 0 and temp[i + 1] < 0):
				ans += 1
		print(ans)


n = int(input())
s = input()
c = 0
q = 0
for i in range(len(s)):
	if s[i] == '(':
		c += 1
	else:
		c += -1
		if c < 0:
			q = q + 2
if c != 0:
	print(-1)
else:
	print(q)


from sys import *
from math import *
n = int(stdin.readline())
s = input()
a = []
for i in range(n):
	if s[i] == '(':
		a.append(1)
	else:
		a.append(-1)
j = -1
if sum(a) != 0:
	print(-1)
else:
	ans = 0
	s = 0
	for i in range(n):
		s += a[i]
		if s == -1 and s - a[i] == 0:
			j = i
		if s == 0:
			if j != -1:
				ans += i - j + 1
				j = -1
	print(ans)


n = int(input())
s = input()
l = 0
r = 0
d = True
c = False
res = 0
for i in range(len(s)):
	if d and s[i] == '(':
		c = True
	d = False
	l += s[i] == '('
	r += s[i] == ')'
	if l == r and c:
		l = r = 0
		d = True
		c = False
	elif l == r and (not c):
		res += l + r
		l = r = 0
		d = True
if l != r:
	res = -1
print(res)


from collections import defaultdict
from queue import deque

def arrinp():
	return [*map(int, input().split(' '))]

def mulinp():
	return map(int, input().split(' '))

def intinp():
	return int(input())

def solution():
	n = intinp()
	a = input()
	op = 0
	cl = 0
	for i in a:
		if i == '(':
			op += 1
		else:
			cl += 1
	if op != cl:
		print(-1)
		return
	balance = 0
	arr = []
	for i in a:
		if i == '(':
			balance += 1
			arr.append(balance)
		else:
			balance -= 1
			arr.append(balance)
	count = 0
	for i in range(len(arr)):
		if arr[i] < 0:
			count += 1
		if arr[i] == 0 and arr[i - 1] <= 0:
			count += 1
	print(count)
testcases = 1
for _ in range(testcases):
	solution()


import sys
input = sys.stdin.readline
n = int(input())
s = input()
ans = [0] * (n + 1)
for i in range(n):
	if s[i] == '(':
		ans[i + 1] += ans[i] + 1
	else:
		ans[i + 1] += ans[i] - 1
if ans[-1] != 0:
	print(-1)
	return
res = 0
flag = False
for i in range(n + 1):
	if ans[i] == -1 and (not flag):
		ind = i
		flag = True
	elif ans[i] == 0 and flag:
		res += i - ind + 1
		flag = False
print(res)


import os
import sys
from io import BytesIO, IOBase
import math

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def binary(n):
	return bin(n).replace('0b', '')

def decimal(s):
	return int(s, 2)

def pow2(n):
	p = 0
	while n > 1:
		n //= 2
		p += 1
	return p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(i)
			n = n / i
	if n > 2:
		l.append(int(n))
	return l

def isPrime(n):
	if n == 1:
		return False
	else:
		root = int(n ** 0.5)
		root += 1
		for i in range(2, root):
			if n % i == 0:
				return False
		return True

def maxPrimeFactors(n):
	maxPrime = -1
	while n % 2 == 0:
		maxPrime = 2
		n >>= 1
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			maxPrime = i
			n = n / i
	if n > 2:
		maxPrime = n
	return int(maxPrime)
n = int(input())
s = input()
if n % 2 == 1:
	print(-1)
elif s.count('(') != n // 2:
	print(-1)
else:
	a = 0
	b = 0
	for i in s:
		if i == ')':
			b -= 1
			if b < 0:
				a += 2
		else:
			b += 1
	print(a)


n = int(input())
string = input()

def checkio(n, string):
	if n % 2 != 0:
		return -1
	opens_counter = string.count('(')
	closes_counter = string.count(')')
	if opens_counter != closes_counter:
		return -1
	uncorrect_counter = 0
	counter = 0
	for i in range(len(string)):
		if string[i] == '(':
			counter += 1
		elif counter > 0:
			counter -= 1
		else:
			counter -= 1
			uncorrect_counter += 1
	return uncorrect_counter * 2
print(checkio(n, string))


n = int(input())
s = input()
ball = 0
now_s = 0
ans = 0
for i in range(n):
	if s[i] == '(':
		ball += 1
		if ball == 0:
			now_s += 1
			ans += now_s
			now_s = 0
	else:
		ball -= 1
	if ball < 0:
		now_s += 1
if ball == 0:
	ans += now_s
	print(ans)
else:
	print(-1)


n = int(input())
s = list(input())
rec = {}
rec['('] = -1
rec[')'] = 1
ans = 0
temp = rec[s[0]]
start = s[0]
l = 1
i = 1
while i < n:
	temp += rec[s[i]]
	l += 1
	if temp == 0:
		if start == ')':
			ans += l
		if i + 1 < n:
			start = s[i + 1]
			temp = rec[s[i + 1]]
			l = 1
			i += 2
			continue
		else:
			break
	i += 1
if temp != 0:
	print(-1)
else:
	print(ans)


n = int(input())
s = input()
if s.count('(') != s.count(')'):
	print(-1)
else:
	f = 0
	start = 0
	close = 0
	ope = 0
	k = 0
	ans = 0
	for i in range(n):
		if s[i] == ')':
			if k == 0:
				k = ')'
				start = i
			close += 1
		elif s[i] == '(':
			if k == 0:
				k = '('
				start = i
			ope += 1
		if ope == close:
			if k == ')':
				ans += i - start + 1
			k = 0
	print(ans)


def balance(list):
	if len(list) % 2 == 1:
		return False
	temp = []
	for i in list:
		if i == '(':
			temp.append('(')
		else:
			if len(temp) == 0:
				return False
			temp.pop(-1)
	return len(temp) == 0

def func(inp, n):
	(open, close) = (0, 0)
	ans = 0
	list = []
	prev = 0
	for i in range(n):
		if inp[i] == '(':
			open += 1
		elif inp[i] == ')':
			close += 1
		if open == close:
			open = 0
			close = 0
			list.append(inp[prev:i + 1])
			prev = i + 1
	for i in list:
		if not balance(i):
			ans += len(i)
	return ans
t = int(input())
inp = input()
count = 0
for i in inp:
	if i == '(':
		count += 1
	else:
		count -= 1
if count != 0:
	print(-1)
else:
	print(func(inp, t))


t = int(input())
s = input()
value = []
for i in range(t):
	if len(value) == 0:
		if s[0] == '(':
			value.append(1)
		else:
			value.append(-1)
		continue
	if s[i] == '(':
		value.append(value[i - 1] + 1)
	else:
		value.append(value[i - 1] - 1)
c = 0
for i in range(len(value)):
	if value[i] < 0:
		c += 1
		continue
	if value[i] == 0 and value[i - 1] < 0:
		c += 1
		continue
if value[-1] == 0:
	print(c)
else:
	print(-1)


t = int(input())
s = input()
if s.count('(') != s.count(')'):
	print(-1)
else:
	ans = []
	negval = 0
	val = 0
	for i in range(len(s)):
		if s[i] == '(':
			val += 1
			if val == 0:
				ans.append(-1)
			else:
				ans.append(val)
		else:
			val -= 1
			ans.append(val)
	a = 0
	for i in ans:
		if i < 0:
			a += 1
	print(a)


n = int(input())
s = str(input())
ctr = 0
negs = 0
for i in range(n):
	if s[i] == '(':
		ctr += 1
	if s[i] == ')':
		ctr -= 1
		if ctr < 0:
			negs += 1
if ctr == 0:
	print(negs * 2)
else:
	print(-1)


n = int(input())
a = input()
x = 0
y = 0
for i in a:
	if i == '(':
		x += 1
	else:
		y += 1
if x != y:
	print(-1)
else:
	(ans, i) = (0, 0)
	t = 0
	b = 0
	l = -1
	while i < n:
		if a[i] == '(':
			if l == -1:
				b += 1
			elif t == 1:
				ans += i - l + 1
				t = 0
				l = -1
			else:
				t -= 1
		elif b != 0:
			b -= 1
		elif t == 0:
			l = i
			t = 1
		else:
			t += 1
		i += 1
	print(ans)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(a, b):
	ans = 1
	while b > 0:
		if b % 2 == 1:
			ans *= a
		a *= a
		b //= 2
	return ans

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def solve():
	n = int(inp())
	a = list(inp())
	ans = 0
	ind = -1
	cnt = [0] * (n + 1)
	if a.count(')') != a.count('('):
		print(-1)
		return
	for i in range(n):
		if a[i] == ')':
			cnt[i] = cnt[i - 1] - 1
		else:
			cnt[i] = cnt[i - 1] + 1
		if cnt[i] == 0 and cnt[i - 1] < 0:
			ans += i - ind
		if cnt[i] == 0:
			ind = i
	print(ans)
testcase(1)


n = int(input())
bracs = input()
if bracs.count('(') != bracs.count(')'):
	print(-1)
else:
	(count, when, ans) = (0, -1, 0)
	for (i, b) in enumerate(bracs):
		if b == '(':
			count += 1
			if count == 0:
				ans += i - when + 1
		else:
			count -= 1
			if count == -1:
				when = i
	print(ans)


def resort(seq):
	if seq.count('(') != seq.count(')'):
		print('-1')
		return
	count = 0
	state = 0
	prev = 0
	for i in seq:
		if i == '(':
			state += 1
		else:
			state -= 1
		if state < 0:
			count += 1
		elif state == 0 and prev < 0:
			count += 1
		prev = state
	if state != 0:
		print(-1)
	else:
		print(count)
seq_length = input()
resort(input())


n = int(input())
s = list(input())
mp = {'(': 1, ')': -1}
val = [mp[s[0]]]
for i in range(1, n):
	val.append(val[-1] + mp[s[i]])
if val[-1]:
	print(-1)
	exit()
prev = -1
ans = 0
for i in range(n):
	if not val[i]:
		if val[i - 1] < 0:
			ans += i - prev
		prev = i
print(ans)


import math
size = int(input())
s = input()
(opn, cls, reord) = (0, 0, 0)
for i in s:
	if i == '(':
		opn = opn + 1
	else:
		cls = cls + 1
		if opn < cls:
			reord += 1
if opn != cls:
	print(-1)
else:
	print(reord * 2)


n = int(input())
s = input()
c1 = s.count('(')
c2 = s.count(')')
if c1 != c2:
	print(-1)
else:
	need = [0] * n
	cnt = 0
	for i in range(n):
		if cnt < 0:
			need[i] = 1
		if s[i] == '(':
			cnt += 1
		elif s[i] == ')':
			cnt -= 1
		else:
			print('error')
		if cnt < 0:
			need[i] = 1
	print(sum(need))


import io, os

def rint():
	return map(int, input().split())

def oint():
	return int(input())
n = oint()
ss = str(input())
s = []
for i in range(n):
	if ss[i] == '(':
		s.append(1)
	else:
		s.append(-1)
if sum(s) != 0:
	print(-1)
	exit()
ps = 0
ans = 0
pi = -1
psp = 0
for i in range(n):
	psp = ps
	ps += s[i]
	if ps == 0:
		if psp < 0:
			ans += i - pi
		pi = i
print(ans)


n = int(input())
a = list(input())
s1 = 0
t = 0
for i in range(n):
	if a[i] == '(':
		s1 += 1
	else:
		s1 -= 1
		if s1 < 0:
			t += 2
if s1 != 0:
	print(-1)
else:
	print(t)


n = int(input())
f = list(input())
if f.count(')') != f.count('('):
	print(-1)
else:
	s = 0
	s2 = 0
	k = 0
	for i in range(len(f)):
		if f[i] == ')':
			if s2 == 0:
				s += 1
			else:
				s2 -= 1
		elif f[i] == '(':
			if s > 0:
				s -= 1
				k += 2
			else:
				s2 += 1
	print(k)


n = input()
s = input()
total = 0
cur = 0
start = None
result = 0
for (i, x) in enumerate(s):
	if x == '(':
		cur += 1
		total += 1
	else:
		cur -= 1
		total -= 1
	if start is None and cur < 0:
		start = i
	if start is not None and cur == 0:
		result += i - start + 1
		start = None
if total != 0:
	print(-1)
else:
	print(result)


n = int(input())
s = input()
aCount = s.count('(')
bCount = s.count(')')
if aCount != bCount:
	print(-1)
else:
	levelCount = 0
	start = 0
	counts = 0
	ans = 0
	for i in range(n):
		if s[i] == ')':
			levelCount -= 1
		else:
			levelCount += 1
		if levelCount < 0:
			start = 1
			counts += 1
		elif levelCount == 0 and start == 1:
			start = 0
			ans += counts + 1
			counts = 0
	print(ans)


n = int(input())
s = str(input())
b = 0
ans = 0
i = 0
while i < n:
	if s[i] == '(':
		b += 1
	if s[i] == ')':
		b -= 1
	if b < 0:
		j = i + 1
		while j < n:
			if b == 0:
				break
			elif s[j] == '(':
				b += 1
			else:
				b -= 1
			j += 1
		ans += j - i
		i = j
		continue
	i += 1
if b == 0:
	print(ans)
else:
	print(-1)


n = int(input())
seq = input()
pref = [0] * n
for i in range(n):
	if seq[i] == '(':
		pref[i] = 1
	elif seq[i] == ')':
		pref[i] = 0
stat = 0
temp = 0
flag = 0
for i in range(n):
	if pref[i] == 1:
		stat += 1
	elif pref[i] == 0:
		stat -= 1
	if stat < 0:
		flag = 1
		temp += 1
	if stat >= 0:
		if flag == 1:
			temp += 1
			flag = 0
if stat != 0:
	print(-1)
else:
	print(temp)


import sys
import bisect
input = sys.stdin.readline
n = int(input())
s = input()
l = []
for i in range(n):
	if s[i] == '(':
		l.append(1)
	else:
		l.append(-1)
z = sum(l)
if z != 0:
	print(-1)
	quit()
ans = 0
ok = 0
for i in range(n):
	ans += l[i]
	if ans < 0:
		ok += 1
	if ans == 0 and l[i] == 1:
		ok += 1
print(ok)


n = int(input())
s = input()
c = 0
f = 0
t = 0
for i in s:
	if i == '(':
		c += 1
		if f == 1 and c == 0:
			t += 1
			f = 0
	elif i == ')':
		if c == 0:
			f = 1
		c -= 1
	if f == 1:
		t += 1
if c == 0:
	print(t)
else:
	print(-1)


n = int(input())
s = input()
num1 = 0
num2 = 0
for i in range(0, n, 1):
	if s[i] == '(':
		num1 = num1 + 1
	else:
		num2 = num2 + 1
if num1 != num2:
	print(-1)
else:
	stack = {}
	num = 0
	ans = 0
	for i in range(0, n, 1):
		if num == 0:
			num = num + 1
			stack[num] = s[i]
			continue
		if s[i] == '(':
			if stack[num] == ')':
				num = num - 1
				ans = ans + 2
			else:
				num = num + 1
				stack[num] = s[i]
		elif stack[num] == '(':
			num = num - 1
		else:
			num = num + 1
			stack[num] = s[i]
	print(ans)