#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;cin>>n;
    string s;cin>>s;
    int t=0,count=0;
    for(int i=0;i<s.size();i++)
    {
        if(s[i]=='(')
            count++;
        else if(count==0)
        {
            count++;
            t++;
        }
        else
            count--;
    }
    if(s.size()%2==1)
        cout<<-1<<endl;
    else
        cout<<t+count<<endl;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;cin>>n;
    string s;cin>>s;
    int count=0;\
    int t=0;
    for(int i=0;i<n;i++)
    {
        if(s[i]=='(')
            count++;
        else
            count--;
        int sum=0;
        while(count<0 && i<n-1)
        {
            i++;
            sum++;
            if(s[i]=='(')
                count++;
            else
                count--;
        }
        if(sum!=0)
            t+=sum+1;
    }
    if(count!=0)
        cout<<-1<<endl;
    else
        cout<<t<<endl;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;cin>>n;
    string s;cin>>s;
    int count=0;\
    int t=0;
    for(int i=0;i<n;i++)
    {
        if(s[i]=='(')
            count++;
        else
            count--;
        int sum=0;
        while(count<0)
        {
            i++;
            sum++;
            if(s[i]=='(')
                count++;
            else
                count--;
        }
        if(sum!=0)
            t+=sum+1;
    }
    if(count!=0)
        cout<<-1<<endl;
    else
        cout<<t<<endl;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;cin>>n;
    string s;cin>>s;
    int t=0,count=0;
    for(int i=0;i<s.size();i++)
    {
        if(s[i]=='(')
            count++;
        else if(count==0)
        {
            count++;
            t++;
        }
        else
            count--;
    }
    if(s.size()%2==1)
        cout<<-1<<endl;
    else
        cout<<t+count/2<<endl;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

template<typename T>
using minpq = priority_queue<T, vector<T>, greater<T>>;

#define ll             long long int
#define endl           '\n'
#define mod            1000000007
#define pi             3.141592653589793238
#define fo(i,n)        for(int i=1;i<=n;i++)
//#define mem(a,b,sz(a)) memset(a,b,sizeof(a));
#define tol(s)         transform(s.begin(),s.end(),s.begin(),::tolower)
#define tou(s)         transform(s.begin(),s.end(),s.begin(),::toupper)
#define all(x)         (x).begin(), (x).end()
#define pb             push_back
#define mt             make_tuple
#define lb             lower_bound
#define ub             upper_bound
#define tr(it, a)      for(auto it = a.begin();it!=a.end();it++)
#define rtr(it, a)     for(auto it = a.rbegin();it!=a.rend();it++)
#define gcd(a,b)       __gcd(a,b)
#define pq             priority_queue
#define fr             first
#define sc             second
#define sz(x)          x.size()
#define T              ll t=0;cin>>t;for(ll test=0;test<t;test++)
#define rep(i,n)       for(__typeof(n) i=0; i<(n); i++)
#define MAX(a)         (*max_element(all(a)))
#define MIN(a)         (*min_element(all(a)))
typedef pair<int, int>  pii;
typedef pair<ll, ll>    pll;
typedef vector<int>     vi;
typedef vector<ll>      vl;
typedef vector<pii>     vpii;
typedef vector<pll>      vpl;
typedef vector<vi>      vvi;
typedef vector<vl>      vvl;

const long long inf=1000000000000;
bool ispalindrome(string s)
{
    ll len=s.length();
    for(ll i=0;i<len;i++){
        if(s[i]!=s[len-i-1])
        return false;
    }
    return true;
}
long long mbinpow(long long a, long long b) {
    long long res = 1;
    while (b > 0) {
        if (b & 1)
            res = (res %mod *a %mod ) %mod ;
        a = (  a %mod *  a %mod  )%mod  ;
        b >>= 1;
    }
    return res%mod;
}
long long binpow(long long a, long long b) {
    long long res = 1;
    while (b > 0) {
        if (b & 1)
            res = (res  *  a  );
            a   = (a    *  a  );
        b >>= 1;
    }
    return res;
}
long long is_prime(long long n)
{
    for(long long i=2;i<=sqrt(n);i++)
    {
        if(n%i==0)return 0;
    }
    return 1;
}

int main()
{
ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif

  ll n;
  cin>>n;
  string s;
  cin>>s;
  vector<int>a,b;
  ll ans=0;
  rep(i,n)
  {
      if(s[i]=='(')
      {
          a.push_back(i);
          if(a.size()==b.size())
          {
          ans+=(a.back()+1-b.front());
          a.clear();
          b.clear();
          }
      }
      else if(s[i]==')')
      {
          if(!a.empty())
          {
              a.pop_back();
          }
          else
          {
              b.push_back(i);
          }
      }
  }
  if(!a.empty() || !b.empty())cout<<-1;
  else
  {
      cout<<ans;
  }

}
/*Deletes all characters except first one     Deletes 4 characters from index number 1
str.erase(1);                               str.erase(1,4);
Deletes character at position 4
 str.erase(str.begin() + 4);
bool compare(const pair<int, int>&a, const pair<int, int>&b)
{
   return a.second<b.second;
}
maxn = max_element(mp.begin(), mp.end(), compare)->second;
bool sortbysec(const pair<int,int> &a, const pair<int,int> &b)
{
    return (a.second < b.second);
}
vector<vector<int> > vec( n , vector<int> (m));
min(a,b,c,d)==min({a,b,c,d});
priority_queue <int, vector<int>, greater<int>> gquiz; // to create min heap
cin.ignore(numeric_limits<streamsize>::max(),'\n');
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};
int dx[] = {+0,+0,+1,-1,-1,+1,-1,+1}; ///King's move
int dy[] = {-1,+1,+0,+0,+1,+1,-1,-1}; ///king's Move
int dx[] = {-2,-2,-1,-1,+1,+1,+2,+2}; ///knight's move
int dy[] = {-1,+1,-2,+2,-2,+2,-1,+1}; ///knight's move
*/


#include<bits/stdc++.h>
using namespace std;

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

template<typename T>
using minpq = priority_queue<T, vector<T>, greater<T>>;

#define ll             long long int
#define endl           '\n'
#define mod            1000000007
#define pi             3.141592653589793238
#define fo(i,n)        for(int i=1;i<=n;i++)
//#define mem(a,b,sz(a)) memset(a,b,sizeof(a));
#define tol(s)         transform(s.begin(),s.end(),s.begin(),::tolower)
#define tou(s)         transform(s.begin(),s.end(),s.begin(),::toupper)
#define all(x)         (x).begin(), (x).end()
#define pb             push_back
#define mt             make_tuple
#define lb             lower_bound
#define ub             upper_bound
#define tr(it, a)      for(auto it = a.begin();it!=a.end();it++)
#define rtr(it, a)     for(auto it = a.rbegin();it!=a.rend();it++)
#define gcd(a,b)       __gcd(a,b)
#define pq             priority_queue
#define fr             first
#define sc             second
#define sz(x)          x.size()
#define T              ll t=0;cin>>t;for(ll test=0;test<t;test++)
#define rep(i,n)       for(__typeof(n) i=0; i<(n); i++)
#define MAX(a)         (*max_element(all(a)))
#define MIN(a)         (*min_element(all(a)))
typedef pair<int, int>  pii;
typedef pair<ll, ll>    pll;
typedef vector<int>     vi;
typedef vector<ll>      vl;
typedef vector<pii>     vpii;
typedef vector<pll>      vpl;
typedef vector<vi>      vvi;
typedef vector<vl>      vvl;

const long long inf=1000000000000;
bool ispalindrome(string s)
{
    ll len=s.length();
    for(ll i=0;i<len;i++){
        if(s[i]!=s[len-i-1])
        return false;
    }
    return true;
}
long long mbinpow(long long a, long long b) {
    long long res = 1;
    while (b > 0) {
        if (b & 1)
            res = (res %mod *a %mod ) %mod ;
        a = (  a %mod *  a %mod  )%mod  ;
        b >>= 1;
    }
    return res%mod;
}
long long binpow(long long a, long long b) {
    long long res = 1;
    while (b > 0) {
        if (b & 1)
            res = (res  *  a  );
            a   = (a    *  a  );
        b >>= 1;
    }
    return res;
}
long long is_prime(long long n)
{
    for(long long i=2;i<=sqrt(n);i++)
    {
        if(n%i==0)return 0;
    }
    return 1;
}

int main()
{
ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif

  ll n;
  cin>>n;
  string s;
  cin>>s;
  vector<int>a,b;
  ll bal=0;
  ll ans=0;
  if(n&1)return cout<<-1,0;
  rep(i,n)
  {
      if(s[i]=='(')
      {
          a.push_back(i);
          if(a.size()==b.size())
          {
              ans+=abs(a.back()+1-b.front());
              debug(ans,bal);
              ans+=2*bal;
              bal=0;
              a.clear();
              b.clear();
          }
      }
      else if(s[i]==')')
      {
          if(!a.empty())
          {
              a.pop_back();
              if(!b.empty())
              bal++;
          }
          else
          {
              b.push_back(i);
          }
      }
  }
  if(!a.empty() || !b.empty())cout<<-1<<endl;
  else cout<<ans<<endl;

}
/*Deletes all characters except first one     Deletes 4 characters from index number 1
str.erase(1);                               str.erase(1,4);
Deletes character at position 4
 str.erase(str.begin() + 4);
bool compare(const pair<int, int>&a, const pair<int, int>&b)
{
   return a.second<b.second;
}
maxn = max_element(mp.begin(), mp.end(), compare)->second;
bool sortbysec(const pair<int,int> &a, const pair<int,int> &b)
{
    return (a.second < b.second);
}
vector<vector<int> > vec( n , vector<int> (m));
min(a,b,c,d)==min({a,b,c,d});
priority_queue <int, vector<int>, greater<int>> gquiz; // to create min heap
cin.ignore(numeric_limits<streamsize>::max(),'\n');
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};
int dx[] = {+0,+0,+1,-1,-1,+1,-1,+1}; ///King's move
int dy[] = {-1,+1,+0,+0,+1,+1,-1,-1}; ///king's Move
int dx[] = {-2,-2,-1,-1,+1,+1,+2,+2}; ///knight's move
int dy[] = {-1,+1,-2,+2,-2,+2,-1,+1}; ///knight's move
*/


#include<bits/stdc++.h>
using namespace std;

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}
template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

template<typename T>
using minpq = priority_queue<T, vector<T>, greater<T>>;

#define ll             long long int
#define endl           '\n'
#define mod            1000000007
#define pi             3.141592653589793238
#define fo(i,n)        for(int i=1;i<=n;i++)
//#define mem(a,b,sz(a)) memset(a,b,sizeof(a));
#define tol(s)         transform(s.begin(),s.end(),s.begin(),::tolower)
#define tou(s)         transform(s.begin(),s.end(),s.begin(),::toupper)
#define all(x)         (x).begin(), (x).end()
#define pb             push_back
#define mt             make_tuple
#define lb             lower_bound
#define ub             upper_bound
#define tr(it, a)      for(auto it = a.begin();it!=a.end();it++)
#define rtr(it, a)     for(auto it = a.rbegin();it!=a.rend();it++)
#define gcd(a,b)       __gcd(a,b)
#define pq             priority_queue
#define fr             first
#define sc             second
#define sz(x)          x.size()
#define T              ll t=0;cin>>t;for(ll test=0;test<t;test++)
#define rep(i,n)       for(__typeof(n) i=0; i<(n); i++)
#define MAX(a)         (*max_element(all(a)))
#define MIN(a)         (*min_element(all(a)))
typedef pair<int, int>  pii;
typedef pair<ll, ll>    pll;
typedef vector<int>     vi;
typedef vector<ll>      vl;
typedef vector<pii>     vpii;
typedef vector<pll>      vpl;
typedef vector<vi>      vvi;
typedef vector<vl>      vvl;

const long long inf=1000000000000;
bool ispalindrome(string s)
{
    ll len=s.length();
    for(ll i=0;i<len;i++){
        if(s[i]!=s[len-i-1])
        return false;
    }
    return true;
}
long long mbinpow(long long a, long long b) {
    long long res = 1;
    while (b > 0) {
        if (b & 1)
            res = (res %mod *a %mod ) %mod ;
        a = (  a %mod *  a %mod  )%mod  ;
        b >>= 1;
    }
    return res%mod;
}
long long binpow(long long a, long long b) {
    long long res = 1;
    while (b > 0) {
        if (b & 1)
            res = (res  *  a  );
            a   = (a    *  a  );
        b >>= 1;
    }
    return res;
}
long long is_prime(long long n)
{
    for(long long i=2;i<=sqrt(n);i++)
    {
        if(n%i==0)return 0;
    }
    return 1;
}

int main()
{
ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif

  ll n;
  cin>>n;
  string s;
  cin>>s;
  vector<int>a,b;
  ll bal=0;
  ll ans=0;
  if(n&1)return cout<<-1,0;
  rep(i,n)
  {
      if(s[i]=='(')
      {
          a.push_back(i);
      }
      else if(s[i]==')')
      {
          if(!a.empty())
          {
              a.pop_back();
          }
          else
          {
              b.push_back(i);
          }
      }
  }
  ll x=a.size();
  ll y=b.size();
  debug(a);
  debug(b);
  if(x!=y)cout<<-1<<endl;
  else
  {
      cout<<(a.back()+1-b.front());
  }

}
/*Deletes all characters except first one     Deletes 4 characters from index number 1
str.erase(1);                               str.erase(1,4);
Deletes character at position 4
 str.erase(str.begin() + 4);
bool compare(const pair<int, int>&a, const pair<int, int>&b)
{
   return a.second<b.second;
}
maxn = max_element(mp.begin(), mp.end(), compare)->second;
bool sortbysec(const pair<int,int> &a, const pair<int,int> &b)
{
    return (a.second < b.second);
}
vector<vector<int> > vec( n , vector<int> (m));
min(a,b,c,d)==min({a,b,c,d});
priority_queue <int, vector<int>, greater<int>> gquiz; // to create min heap
cin.ignore(numeric_limits<streamsize>::max(),'\n');
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};
int dx[] = {+0,+0,+1,-1,-1,+1,-1,+1}; ///King's move
int dy[] = {-1,+1,+0,+0,+1,+1,-1,-1}; ///king's Move
int dx[] = {-2,-2,-1,-1,+1,+1,+2,+2}; ///knight's move
int dy[] = {-1,+1,-2,+2,-2,+2,-1,+1}; ///knight's move
*/


#include<bits/stdc++.h>
using namespace std;

long long GCD(long long a, long long b)
{
    if(b==0)
        return a;
    return GCD(b, a % b);

}

long long LCM(long long a, long long b)
{
    long long gcd=GCD(a,b);
     return (a*b)/gcd;
}

int main()
{
    long long i, j, k, n, m, t, x, y, s=0, c=0, l=0;
    string a;
    cin >> n >> a;
    for(i=0; i<n; i++)
    {
        if(a[i]=='(')
            s++;
        else
        {
            c++;
        }
    }
    if(s!=c)
        cout << "-1";
    else
    {
        s=0;
        for(i=0; i<n; i++)
        {
            c=0;
            if(a[i]=='(')
            {
                if(l>0)
                {
                    l--;
                    a[i]='|';
                }
                else
                {
                    for(j=i+1; j<n; j++)
                    {
                        if(a[j]==')')
                        {
                        a[i]='|';
                        a[j]='|';
                        c=1;
                        break;
                        }
                    }
                    if(c==0)
                        s+=2;
                }
            }
            else if(a[i]==')')
            {
                l++;
                s+=2;
            }
            if(l<0)
                l=0;
        }
        cout <<s << endl;
    }

}


#include<bits/stdc++.h>
using namespace std;

long long GCD(long long a, long long b)
{
    if(b==0)
        return a;
    return GCD(b, a % b);

}

long long LCM(long long a, long long b)
{
    long long gcd=GCD(a,b);
     return (a*b)/gcd;
}

int main()
{
    long long i, j, k, n, m, t, x=0, y=0, s=0, c=0, l=0;
    string a;
    cin >> n >> a;
    for(i=0; i<n; i++)
    {
        if(a[i]=='(')
            s++;
        else
        {
            c++;
        }
    }
    if(s!=c)
        cout << "-1";
    else
    {
        s=0;
        for(i=0; i<n; i++)
        {
            if(a[i]==')')
            {
                if(x<=0)
                {
                    s+=2;
                    x--;
                }
                else
                {
                    x--;
                }
            }
            else if(a[i]=='(')
            {
                x++;
            }
        }
        cout <<s << endl;
    }

}


#include<bits/stdc++.h>
using namespace std;

long long GCD(long long a, long long b)
{
    if(b==0)
        return a;
    return GCD(b, a % b);

}

long long LCM(long long a, long long b)
{
    long long gcd=GCD(a,b);
     return (a*b)/gcd;
}

int main()
{
    long long i, j, k, n, m, t, x, y, s=0, c=0, l;
    string a;
    cin >> n >> a;
    for(i=0; i<n; i++)
    {
        if(a[i]=='(')
            s++;
        else
        {
            c++;
        }
    }
    if(s!=c)
        cout << "-1";
    else
    {
        s=0;
        for(i=0; i<n; i++)
        {
            if(a[i]=='(')
            {
                for(j=i+1; j<n; j++)
                {
                    if(a[j]==')')
                    {
                        a[i]='|';
                        a[j]='|';
                        break;
                    }
                }
            }
            else if(a[i]==')')
            {
                for(j=i+1; j<n; j++)
                {
                    if(a[j]=='(')
                    {
                        a[i]='|';
                        a[j]='|';
                        break;
                    }
                }
                s+=2;
            }
        }
        cout <<s << endl;
    }

}


#include<bits/stdc++.h>
using namespace std;

long long GCD(long long a, long long b)
{
    if(b==0)
        return a;
    return GCD(b, a % b);

}

long long LCM(long long a, long long b)
{
    long long gcd=GCD(a,b);
     return (a*b)/gcd;
}

int main()
{
    long long i, j, k, n, m, t, x, y, s=0, c=0, l=0;
    string a;
    cin >> n >> a;
    for(i=0; i<n; i++)
    {
        if(a[i]=='(')
            s++;
        else
        {
            c++;
        }
    }
    if(s!=c)
        cout << "-1";
    else
    {
        s=0;
        for(i=0; i<n; i++)
        {
            c=0;
            if(a[i]=='(')
            {
                if(l==1)
                {
                    l=0;
                    a[i]='|';
                }
                else
                {
                    for(j=i+1; j<n; j++)
                    {
                        if(a[j]==')')
                        {
                        a[i]='|';
                        a[j]='|';
                        c=1;
                        break;
                        }
                    }
                    if(c==0)
                        s+=2;
                }
            }
            else if(a[i]==')')
            {
                l=1;
                s+=2;
            }
        }
        cout <<s << endl;
    }

}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double ld;
typedef double db;
typedef string str;

typedef pair<int,int> pi;
typedef pair<ll,ll> pl;
typedef pair<db,db> pd;

typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<db> vd;
typedef vector<str> vs;
typedef vector<pi> vpi;
typedef vector<pl> vpl;
typedef vector<pd> vpd;

#define mp make_pair
#define f first
#define s second
#define sz(x) (int)x.size()
#define all(x) begin(x), end(x)
#define rall(x) (x).rbegin(), (x).rend()
#define rsz resize
#define ins insert
#define ft front()
#define bk back()
#define pf push_front
#define pb push_back
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound

#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)

const int MOD = 1e9+7; // 998244353;
const int MX = 2e5+5;
const ll INF = 1e18;
const ld PI = acos((ld)-1);
const int xd[4] = {1,0,-1,0}, yd[4] = {0,1,0,-1};

template<class T> bool ckmin(T& a, const T& b) {
	return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) {
	return a < b ? a = b, 1 : 0; }
int pct(int x) { return __builtin_popcount(x); }
int bit(int x) { return 31-__builtin_clz(x); } // floor(log2(x))
int cdiv(int a, int b) { return a/b+!(a<0||a%b == 0); } // division of a by b rounded up, assumes b > 0

namespace input {
	template<class T> void re(complex<T>& x);
	template<class T1, class T2> void re(pair<T1,T2>& p);
	template<class T> void re(vector<T>& a);
	template<class T, size_t SZ> void re(array<T,SZ>& a);

	template<class T> void re(T& x) { cin >> x; }
	void re(double& x) { string t; re(t); x = stod(t); }
	void re(ld& x) { string t; re(t); x = stold(t); }
	template<class T, class... Ts> void re(T& t, Ts&... ts) {
		re(t); re(ts...);
	}

	template<class T> void re(complex<T>& x) { T a,b; re(a,b); x = {a,b}; }
	template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.f,p.s); }
	template<class T> void re(vector<T>& a) { F0R(i,sz(a)) re(a[i]); }
	template<class T, size_t SZ> void re(array<T,SZ>& a) { F0R(i,SZ) re(a[i]); }
}

using namespace input;

namespace output {
	void pr(int x) { cout << x; }
	void pr(long x) { cout << x; }
	void pr(ll x) { cout << x; }
	void pr(unsigned x) { cout << x; }
	void pr(unsigned long x) { cout << x; }
	void pr(unsigned long long x) { cout << x; }
	void pr(float x) { cout << x; }
	void pr(double x) { cout << x; }
	void pr(ld x) { cout << x; }
	void pr(char x) { cout << x; }
	void pr(const char* x) { cout << x; }
	void pr(const string& x) { cout << x; }
	void pr(bool x) { pr(x ? "true" : "false"); }
	template<class T> void pr(const complex<T>& x) { cout << x; }

	template<class T1, class T2> void pr(const pair<T1,T2>& x);
	template<class T> void pr(const T& x);

	template<class T, class... Ts> void pr(const T& t, const Ts&... ts) {
		pr(t); pr(ts...);
	}
	template<class T1, class T2> void pr(const pair<T1,T2>& x) {
		pr("{",x.f,", ",x.s,"}");
	}
	template<class T> void pr(const T& x) {
		pr("{"); // const iterator needed for vector<bool>
		bool fst = 1; for (const auto& a: x) pr(!fst?", ":"",a), fst = 0;
		pr("}");
	}

	void ps() { pr("\n"); } // print w/ spaces
	template<class T, class... Ts> void ps(const T& t, const Ts&... ts) {
		pr(t); if (sizeof...(ts)) pr(" "); ps(ts...);
	}

	void pc() { pr("]\n"); } // debug w/ commas
	template<class T, class... Ts> void pc(const T& t, const Ts&... ts) {
		pr(t); if (sizeof...(ts)) pr(", "); pc(ts...);
	}
	#define dbg(x...) pr("[",#x,"] = ["), pc(x);
}

using namespace output;

namespace io {
	void setIn(string s) { freopen(s.c_str(),"r",stdin); }
	void setOut(string s) { freopen(s.c_str(),"w",stdout); }
	void setIO(string s = "") {
		ios_base::sync_with_stdio(0); cin.tie(0); // fast I/O
		// cin.exceptions(cin.failbit);
		// throws exception when do smth illegal
		// ex. try to read letter into int
		if (sz(s)) { setIn(s+".in"), setOut(s+".out"); } // for USACO
	}
}

using namespace io;

mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());

int n;

int main() {
	setIO(); re(n);
	vi v;
	str s; re(s);
	int dif = 0, cnt = 0;
	vi dumb;
	trav(c,s) {
		if (c == '(') dif ++;
		else dif --;
		cnt ++;
		dumb.pb(dif < 0);
	}
	if (dif != 0) {
		ps(-1);
		exit(0);
	}
	int ans = 0;
	for (int i = 0; i < sz(s); ) {
		if (dumb[i] == 0) { i ++; continue; }
		int I = i;
		while (i < sz(s) && dumb[i]) i ++;
		ans += i-I+1;
	}
	ps(ans);
	// ps(dumb);
	// you should actually read the stuff at the bottom
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double ld;
typedef double db;
typedef string str;

typedef pair<int,int> pi;
typedef pair<ll,ll> pl;
typedef pair<db,db> pd;

typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<db> vd;
typedef vector<str> vs;
typedef vector<pi> vpi;
typedef vector<pl> vpl;
typedef vector<pd> vpd;

#define mp make_pair
#define f first
#define s second
#define sz(x) (int)x.size()
#define all(x) begin(x), end(x)
#define rall(x) (x).rbegin(), (x).rend()
#define rsz resize
#define ins insert
#define ft front()
#define bk back()
#define pf push_front
#define pb push_back
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound

#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)

const int MOD = 1e9+7; // 998244353;
const int MX = 2e5+5;
const ll INF = 1e18;
const ld PI = acos((ld)-1);
const int xd[4] = {1,0,-1,0}, yd[4] = {0,1,0,-1};

template<class T> bool ckmin(T& a, const T& b) {
	return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) {
	return a < b ? a = b, 1 : 0; }
int pct(int x) { return __builtin_popcount(x); }
int bit(int x) { return 31-__builtin_clz(x); } // floor(log2(x))
int cdiv(int a, int b) { return a/b+!(a<0||a%b == 0); } // division of a by b rounded up, assumes b > 0

namespace input {
	template<class T> void re(complex<T>& x);
	template<class T1, class T2> void re(pair<T1,T2>& p);
	template<class T> void re(vector<T>& a);
	template<class T, size_t SZ> void re(array<T,SZ>& a);

	template<class T> void re(T& x) { cin >> x; }
	void re(double& x) { string t; re(t); x = stod(t); }
	void re(ld& x) { string t; re(t); x = stold(t); }
	template<class T, class... Ts> void re(T& t, Ts&... ts) {
		re(t); re(ts...);
	}

	template<class T> void re(complex<T>& x) { T a,b; re(a,b); x = {a,b}; }
	template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.f,p.s); }
	template<class T> void re(vector<T>& a) { F0R(i,sz(a)) re(a[i]); }
	template<class T, size_t SZ> void re(array<T,SZ>& a) { F0R(i,SZ) re(a[i]); }
}

using namespace input;

namespace output {
	void pr(int x) { cout << x; }
	void pr(long x) { cout << x; }
	void pr(ll x) { cout << x; }
	void pr(unsigned x) { cout << x; }
	void pr(unsigned long x) { cout << x; }
	void pr(unsigned long long x) { cout << x; }
	void pr(float x) { cout << x; }
	void pr(double x) { cout << x; }
	void pr(ld x) { cout << x; }
	void pr(char x) { cout << x; }
	void pr(const char* x) { cout << x; }
	void pr(const string& x) { cout << x; }
	void pr(bool x) { pr(x ? "true" : "false"); }
	template<class T> void pr(const complex<T>& x) { cout << x; }

	template<class T1, class T2> void pr(const pair<T1,T2>& x);
	template<class T> void pr(const T& x);

	template<class T, class... Ts> void pr(const T& t, const Ts&... ts) {
		pr(t); pr(ts...);
	}
	template<class T1, class T2> void pr(const pair<T1,T2>& x) {
		pr("{",x.f,", ",x.s,"}");
	}
	template<class T> void pr(const T& x) {
		pr("{"); // const iterator needed for vector<bool>
		bool fst = 1; for (const auto& a: x) pr(!fst?", ":"",a), fst = 0;
		pr("}");
	}

	void ps() { pr("
"); } // print w/ spaces
	template<class T, class... Ts> void ps(const T& t, const Ts&... ts) {
		pr(t); if (sizeof...(ts)) pr(" "); ps(ts...);
	}

	void pc() { pr("]
"); } // debug w/ commas
	template<class T, class... Ts> void pc(const T& t, const Ts&... ts) {
		pr(t); if (sizeof...(ts)) pr(", "); pc(ts...);
	}
	#define dbg(x...) pr("[",#x,"] = ["), pc(x);
}

using namespace output;

namespace io {
	void setIn(string s) { freopen(s.c_str(),"r",stdin); }
	void setOut(string s) { freopen(s.c_str(),"w",stdout); }
	void setIO(string s = "") {
		ios_base::sync_with_stdio(0); cin.tie(0); // fast I/O
		// cin.exceptions(cin.failbit);
		// throws exception when do smth illegal
		// ex. try to read letter into int
		if (sz(s)) { setIn(s+".in"), setOut(s+".out"); } // for USACO
	}
}

using namespace io;

mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());

int n;

int main() {
	setIO(); re(n);
	vi v;
	str s; re(s);
	int dif = 0, cnt = 0;
	vi dumb;
	trav(c,s) {
		if (c == '(') dif ++;
		else dif --;
		cnt ++;
		dumb.pb(dif < 0);
	}
	if (dif != 0) {
		ps(-1);
		exit(0);
	}
	int ans = 0;
	for (int i = 0; i < sz(s); ) {
		if (dumb[i] == 0) { i ++; continue; }
		int I = i;
		while (i < sz(s) && dumb[i]) i ++;
		ans += i-I+1;
	}
	ps(ans);
	// ps(dumb);
	// you should actually read the stuff at the bottom
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double ld;
typedef double db;
typedef string str;

typedef pair<int,int> pi;
typedef pair<ll,ll> pl;
typedef pair<db,db> pd;

typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<db> vd;
typedef vector<str> vs;
typedef vector<pi> vpi;
typedef vector<pl> vpl;
typedef vector<pd> vpd;

#define mp make_pair
#define f first
#define s second
#define sz(x) (int)x.size()
#define all(x) begin(x), end(x)
#define rall(x) (x).rbegin(), (x).rend()
#define rsz resize
#define ins insert
#define ft front()
#define bk back()
#define pf push_front
#define pb push_back
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound

#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)

const int MOD = 1e9+7; // 998244353;
const int MX = 2e5+5;
const ll INF = 1e18;
const ld PI = acos((ld)-1);
const int xd[4] = {1,0,-1,0}, yd[4] = {0,1,0,-1};

template<class T> bool ckmin(T& a, const T& b) {
	return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) {
	return a < b ? a = b, 1 : 0; }
int pct(int x) { return __builtin_popcount(x); }
int bit(int x) { return 31-__builtin_clz(x); } // floor(log2(x))
int cdiv(int a, int b) { return a/b+!(a<0||a%b == 0); } // division of a by b rounded up, assumes b > 0

namespace input {
	template<class T> void re(complex<T>& x);
	template<class T1, class T2> void re(pair<T1,T2>& p);
	template<class T> void re(vector<T>& a);
	template<class T, size_t SZ> void re(array<T,SZ>& a);

	template<class T> void re(T& x) { cin >> x; }
	void re(double& x) { string t; re(t); x = stod(t); }
	void re(ld& x) { string t; re(t); x = stold(t); }
	template<class T, class... Ts> void re(T& t, Ts&... ts) {
		re(t); re(ts...);
	}

	template<class T> void re(complex<T>& x) { T a,b; re(a,b); x = {a,b}; }
	template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.f,p.s); }
	template<class T> void re(vector<T>& a) { F0R(i,sz(a)) re(a[i]); }
	template<class T, size_t SZ> void re(array<T,SZ>& a) { F0R(i,SZ) re(a[i]); }
}

using namespace input;

namespace output {
	void pr(int x) { cout << x; }
	void pr(long x) { cout << x; }
	void pr(ll x) { cout << x; }
	void pr(unsigned x) { cout << x; }
	void pr(unsigned long x) { cout << x; }
	void pr(unsigned long long x) { cout << x; }
	void pr(float x) { cout << x; }
	void pr(double x) { cout << x; }
	void pr(ld x) { cout << x; }
	void pr(char x) { cout << x; }
	void pr(const char* x) { cout << x; }
	void pr(const string& x) { cout << x; }
	void pr(bool x) { pr(x ? "true" : "false"); }
	template<class T> void pr(const complex<T>& x) { cout << x; }

	template<class T1, class T2> void pr(const pair<T1,T2>& x);
	template<class T> void pr(const T& x);

	template<class T, class... Ts> void pr(const T& t, const Ts&... ts) {
		pr(t); pr(ts...);
	}
	template<class T1, class T2> void pr(const pair<T1,T2>& x) {
		pr("{",x.f,", ",x.s,"}");
	}
	template<class T> void pr(const T& x) {
		pr("{"); // const iterator needed for vector<bool>
		bool fst = 1; for (const auto& a: x) pr(!fst?", ":"",a), fst = 0;
		pr("}");
	}

	void ps() { pr("\n"); } // print w/ spaces
	template<class T, class... Ts> void ps(const T& t, const Ts&... ts) {
		pr(t); if (sizeof...(ts)) pr(" "); ps(ts...);
	}

	void pc() { pr("]\n"); } // debug w/ commas
	template<class T, class... Ts> void pc(const T& t, const Ts&... ts) {
		pr(t); if (sizeof...(ts)) pr(", "); pc(ts...);
	}
	#define dbg(x...) pr("[",#x,"] = ["), pc(x);
}

using namespace output;

namespace io {
	void setIn(string s) { freopen(s.c_str(),"r",stdin); }
	void setOut(string s) { freopen(s.c_str(),"w",stdout); }
	void setIO(string s = "") {
		ios_base::sync_with_stdio(0); cin.tie(0); // fast I/O
		// cin.exceptions(cin.failbit);
		// throws exception when do smth illegal
		// ex. try to read letter into int
		if (sz(s)) { setIn(s+".in"), setOut(s+".out"); } // for USACO
	}
}

using namespace io;

mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());

int n;

int main() {
	setIO(); re(n);
	vi v;
	str s; re(s);
	int dif = 0, cnt = 0;
	vi dumb;
	trav(c,s) {
		if (c == '(') dif ++;
		else dif --;
		cnt ++;
		dumb.pb(dif < 0);
	}
	if (dif != 0) {
		ps(-1);
		exit(0);
	}
	int ans = 0;
	for (int i = 0; i < sz(s); ) {
		if (dumb[i] == 0) { i ++; continue; }
		int I = i;
		while (i < sz(s) && dumb[i]) i ++;
		ans += i-I+1;
	}
	ps(ans);
	// ps(dumb);
	// you should actually read the stuff at the bottom
}

/* stuff you should look for
	* int overflow, array bounds
	* special cases (n=1?)
	* do smth instead of nothing and stay organized
	* WRITE STUFF DOWN
*/


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double ld;
typedef double db;
typedef string str;

typedef pair<int,int> pi;
typedef pair<ll,ll> pl;
typedef pair<db,db> pd;

typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<db> vd;
typedef vector<str> vs;
typedef vector<pi> vpi;
typedef vector<pl> vpl;
typedef vector<pd> vpd;

#define mp make_pair
#define f first
#define s second
#define sz(x) (int)x.size()
#define all(x) begin(x), end(x)
#define rall(x) (x).rbegin(), (x).rend()
#define rsz resize
#define ins insert
#define ft front()
#define bk back()
#define pf push_front
#define pb push_back
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound

#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)

const int MOD = 1e9+7; // 998244353;
const int MX = 2e5+5;
const ll INF = 1e18;
const ld PI = acos((ld)-1);
const int xd[4] = {1,0,-1,0}, yd[4] = {0,1,0,-1};

template<class T> bool ckmin(T& a, const T& b) {
	return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) {
	return a < b ? a = b, 1 : 0; }
int pct(int x) { return __builtin_popcount(x); }
int bit(int x) { return 31-__builtin_clz(x); } // floor(log2(x))
int cdiv(int a, int b) { return a/b+!(a<0||a%b == 0); } // division of a by b rounded up, assumes b > 0

namespace input {
	template<class T> void re(complex<T>& x);
	template<class T1, class T2> void re(pair<T1,T2>& p);
	template<class T> void re(vector<T>& a);
	template<class T, size_t SZ> void re(array<T,SZ>& a);

	template<class T> void re(T& x) { cin >> x; }
	void re(double& x) { string t; re(t); x = stod(t); }
	void re(ld& x) { string t; re(t); x = stold(t); }
	template<class T, class... Ts> void re(T& t, Ts&... ts) {
		re(t); re(ts...);
	}

	template<class T> void re(complex<T>& x) { T a,b; re(a,b); x = {a,b}; }
	template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.f,p.s); }
	template<class T> void re(vector<T>& a) { F0R(i,sz(a)) re(a[i]); }
	template<class T, size_t SZ> void re(array<T,SZ>& a) { F0R(i,SZ) re(a[i]); }
}

using namespace input;

namespace output {
	void pr(int x) { cout << x; }
	void pr(long x) { cout << x; }
	void pr(ll x) { cout << x; }
	void pr(unsigned x) { cout << x; }
	void pr(unsigned long x) { cout << x; }
	void pr(unsigned long long x) { cout << x; }
	void pr(float x) { cout << x; }
	void pr(double x) { cout << x; }
	void pr(ld x) { cout << x; }
	void pr(char x) { cout << x; }
	void pr(const char* x) { cout << x; }
	void pr(const string& x) { cout << x; }
	void pr(bool x) { pr(x ? "true" : "false"); }
	template<class T> void pr(const complex<T>& x) { cout << x; }

	template<class T1, class T2> void pr(const pair<T1,T2>& x);
	template<class T> void pr(const T& x);

	template<class T, class... Ts> void pr(const T& t, const Ts&... ts) {
		pr(t); pr(ts...);
	}
	template<class T1, class T2> void pr(const pair<T1,T2>& x) {
		pr("{",x.f,", ",x.s,"}");
	}
	template<class T> void pr(const T& x) {
		pr("{"); // const iterator needed for vector<bool>
		bool fst = 1; for (const auto& a: x) pr(!fst?", ":"",a), fst = 0;
		pr("}");
	}

	void ps() { pr("\n"); } // print w/ spaces
	template<class T, class... Ts> void ps(const T& t, const Ts&... ts) {
		pr(t); if (sizeof...(ts)) pr(" "); ps(ts...);
	}

	void pc() { pr("]\n"); } // debug w/ commas
	template<class T, class... Ts> void pc(const T& t, const Ts&... ts) {
		pr(t); if (sizeof...(ts)) pr(", "); pc(ts...);
	}
	#define dbg(x...) pr("[",#x,"] = ["), pc(x);
}

using namespace output;

namespace io {
	void setIn(string s) { freopen(s.c_str(),"r",stdin); }
	void setOut(string s) { freopen(s.c_str(),"w",stdout); }
	void setIO(string s = "") {
		ios_base::sync_with_stdio(0); cin.tie(0); // fast I/O
		// cin.exceptions(cin.failbit);
		// throws exception when do smth illegal
		// ex. try to read letter into int
		if (sz(s)) { setIn(s+".in"), setOut(s+".out"); } // for USACO
	}
}

using namespace io;

mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());

int n;

int main() {
	setIO(); re(n);
	vi v;
	str s; re(s);
	int dif = 0, cnt = 0;
	vi dumb;
	trav(c,s) {
		if (c == '(') dif ++;
		else dif --;
		cnt ++;
		dumb.pb(dif < 0);
	}
	if (dif != 0) {
		ps(-1)
		exit(0);
	}
	int ans = 0;
	for (int i = 0; i < sz(s); ) {
		if (dumb[i] == 0) { i ++; continue; }
		int I = i;
		while (i < sz(s) && dumb[i]) i ++;
		ans += i-I+1;
	}
	ps(ans);
	// ps(dumb);
	// you should actually read the stuff at the bottom
}

/* stuff you should look for
	* int overflow, array bounds
	* special cases (n=1?)
	* do smth instead of nothing and stay organized
	* WRITE STUFF DOWN
*/


#include <bits/stdc++.h>
using namespace std;

typedef long double ld;
typedef double db;
typedef string str;

typedef pair<int,int> pi;
typedef pair<ll,ll> pl;
typedef pair<db,db> pd;

typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<db> vd;
typedef vector<str> vs;
typedef vector<pi> vpi;
typedef vector<pl> vpl;
typedef vector<pd> vpd;

#define mp make_pair
#define f first
#define s second
#define sz(x) (int)x.size()
#define all(x) begin(x), end(x)
#define rall(x) (x).rbegin(), (x).rend()
#define rsz resize
#define ins insert
#define ft front()
#define bk back()
#define pf push_front
#define pb push_back
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound

#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)

const int MOD = 1e9+7; // 998244353;
const int MX = 2e5+5;
const ll INF = 1e18;
const ld PI = acos((ld)-1);
const int xd[4] = {1,0,-1,0}, yd[4] = {0,1,0,-1};

template<class T> bool ckmin(T& a, const T& b) {
	return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) {
	return a < b ? a = b, 1 : 0; }
int pct(int x) { return __builtin_popcount(x); }
int bit(int x) { return 31-__builtin_clz(x); } // floor(log2(x))
int cdiv(int a, int b) { return a/b+!(a<0||a%b == 0); } // division of a by b rounded up, assumes b > 0

namespace input {
	template<class T> void re(complex<T>& x);
	template<class T1, class T2> void re(pair<T1,T2>& p);
	template<class T> void re(vector<T>& a);
	template<class T, size_t SZ> void re(array<T,SZ>& a);

	template<class T> void re(T& x) { cin >> x; }
	void re(double& x) { string t; re(t); x = stod(t); }
	void re(ld& x) { string t; re(t); x = stold(t); }
	template<class T, class... Ts> void re(T& t, Ts&... ts) {
		re(t); re(ts...);
	}

	template<class T> void re(complex<T>& x) { T a,b; re(a,b); x = {a,b}; }
	template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.f,p.s); }
	template<class T> void re(vector<T>& a) { F0R(i,sz(a)) re(a[i]); }
	template<class T, size_t SZ> void re(array<T,SZ>& a) { F0R(i,SZ) re(a[i]); }
}

using namespace input;

namespace output {
	void pr(int x) { cout << x; }
	void pr(long x) { cout << x; }
	void pr(ll x) { cout << x; }
	void pr(unsigned x) { cout << x; }
	void pr(unsigned long x) { cout << x; }
	void pr(unsigned long long x) { cout << x; }
	void pr(float x) { cout << x; }
	void pr(double x) { cout << x; }
	void pr(ld x) { cout << x; }
	void pr(char x) { cout << x; }
	void pr(const char* x) { cout << x; }
	void pr(const string& x) { cout << x; }
	void pr(bool x) { pr(x ? "true" : "false"); }
	template<class T> void pr(const complex<T>& x) { cout << x; }

	template<class T1, class T2> void pr(const pair<T1,T2>& x);
	template<class T> void pr(const T& x);

	template<class T, class... Ts> void pr(const T& t, const Ts&... ts) {
		pr(t); pr(ts...);
	}
	template<class T1, class T2> void pr(const pair<T1,T2>& x) {
		pr("{",x.f,", ",x.s,"}");
	}
	template<class T> void pr(const T& x) {
		pr("{"); // const iterator needed for vector<bool>
		bool fst = 1; for (const auto& a: x) pr(!fst?", ":"",a), fst = 0;
		pr("}");
	}

	void ps() { pr("\n"); } // print w/ spaces
	template<class T, class... Ts> void ps(const T& t, const Ts&... ts) {
		pr(t); if (sizeof...(ts)) pr(" "); ps(ts...);
	}

	void pc() { pr("]\n"); } // debug w/ commas
	template<class T, class... Ts> void pc(const T& t, const Ts&... ts) {
		pr(t); if (sizeof...(ts)) pr(", "); pc(ts...);
	}
	#define dbg(x...) pr("[",#x,"] = ["), pc(x);
}

using namespace output;

namespace io {
	void setIn(string s) { freopen(s.c_str(),"r",stdin); }
	void setOut(string s) { freopen(s.c_str(),"w",stdout); }
	void setIO(string s = "") {
		ios_base::sync_with_stdio(0); cin.tie(0); // fast I/O
		// cin.exceptions(cin.failbit);
		// throws exception when do smth illegal
		// ex. try to read letter into int
		if (sz(s)) { setIn(s+".in"), setOut(s+".out"); } // for USACO
	}
}

using namespace io;

mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());

int n;

int main() {
	setIO(); re(n);
	vi v;
	str s; re(s);
	int dif = 0, cnt = 0;
	vi dumb;
	trav(c,s) {
		if (c == '(') dif ++;
		else dif --;
		cnt ++;
		dumb.pb(dif < 0);
	}
	if (dif != 0) {
		ps(-1);
		exit(0);
	}
	int ans = 0;
	for (int i = 0; i < sz(s); ) {
		if (dumb[i] == 0) { i ++; continue; }
		int I = i;
		while (i < sz(s) && dumb[i]) i ++;
		ans += i-I+1;
	}
	ps(ans);
	// ps(dumb);
	// you should actually read the stuff at the bottom
}


#include<bits/stdc++.h>
using namespace std;

int main(){

	int n;
	cin >> n;
	string s;
	cin >> s;
	int open = 0;
	int close = 0;
	if(n%2){
		cout << -1 << endl;
		return 0;
	}
	for(int i = 0 ; i < n ; i++){
		if(s[i] == ')'){
			close++;
		}
		if(s[i] == '('){
			open++;
		}
	}
	if(close != open){
		cout << -1 << endl;
		return 0;
	}
	int ans = 0;
	int temp = 0;
	int last_idx = 0;
	bool activate = true;
	for(int i = 0 ; i < n; i++){
		if(s[i] == ')'){
			temp-=1;
		}
		else if(s[i] == '('){
			temp+=1;
		}
		if(temp < 0){
			activate = true;
		}
		if(temp == 0 && activate){
			ans+=(i - last_idx + 1);
			// cout << i << " " << last_idx << " " <<  i - last_idx + 1 << endl;
			last_idx = i+1;
			activate = false;
		}
		else if(temp == 0){
			last_idx = i+1;
		}
	}
	cout << ans << endl;
}

// 6
// 1 2
// 3 4 5

// 6(1,2)
// 1(1,3)
// 2(2,3)
// 3(1,4)
// 4(2,4)
// 5(3,4)


#include<bits/stdc++.h>
using namespace std;

int main(){

	int n;
	cin >> n;
	string s;
	cin >> s;
	int open = 0;
	int close = 0;
	if(n%2){
		cout << -1 << endl;
		return 0;
	}
	for(int i = 0 ; i < n ; i++){
		if(s[i] == ')'){
			close++;
		}
		if(s[i] == '('){
			open++;
		}
	}
	if(close != open){
		cout << -1 << endl;
		return 0;
	}
	int ans = 0;
	int temp = 0;
	int last_idx = 0;
	bool activate = false;
	for(int i = 0 ; i < n; i++){
		if(s[i] == ')'){
			temp-=1;
		}
		else if(s[i] == '('){
			temp+=1;
		}
		if(temp < 0){
			activate = true;
		}
		if(temp == 0 && activate){
			ans+=(i - last_idx + 1);
			// cout << i << " " << last_idx << " " <<  i - last_idx + 1 << endl;
			last_idx = i+1;
			activate = false;
		}
		else if(temp == 0){
			last_idx = i+1;
		}
	}
	cout << ans << endl;
}


#include<bits/stdc++.h>
using namespace std;
// 1 2 5 5 7 100

int main()
{

    int n,k;
    cin >> n >> k;
    for(int i = 0 ; i < n ; i++){
        for(int j = 0 ; j < n ; j++){
            if(i == j){

                cout << k << " ";

            }
            else
            {
                cout << 0 << " ";
            }
        }
        cout << endl;
    }

}


#include<bits/stdc++.h>
using namespace std;

int main(){

	int n;
	cin >> n;
	string s;
	cin >> s;
	int open = 0;
	int close = 0;
	if(n%2){
		cout << -1 << endl;
		return 0;
	}
	for(int i = 0 ; i < n ; i++){
		if(s[i] == ')'){
			close++;
		}
		if(s[i] == '('){
			open++;
		}
	}
	if(close != open){
		cout << -1 << endl;
		return 0;
	}
	int ans = 0;
	int temp = 0;
	int last_idx = 0;
	bool activate = false;
	for(int i = 0 ; i < n; i++){
		if(s[i] == ')'){
			temp-=1;
		}
		else if(s[i] == '('){
			temp+=1;
		}
		if(temp < 0){
			activate = true;
		}
		if(temp == 0 && activate){
			ans+=(i - last_idx + 1);
			// cout << i << " " << last_idx << " " <<  i - last_idx + 1 << endl;
			last_idx = i+1;
			activate = false;
		}
		else if(temp == 0){
			last_idx = i+1;
		}
	}
	cout << ans << endl;
}

// 6
// 1 2
// 3 4 5

// 6(1,2)
// 1(1,3)
// 2(2,3)
// 3(1,4)
// 4(2,4)
// 5(3,4)

// (())))((


//#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <iterator>
#include <set>
#include <algorithm>
#include <cmath>
#define ll long long
using namespace std;

int main()
{
    //cout<<"Mike"<<endl;
    int n,cnt=0;
    cin>>n;
    int v,k=0;
    char c;
    cin>>c;
    if(c=='(')
    {
        v=1;
    }
    else
    {
        v=-1;
        k=v;
        cnt++;
    }
    for(ll i=1;i<n;i++)
    {
        cin>>c;
        if(c=='(')
        {
            v=v+1;
        }
        else
        {
            v=v-1;
        }
        if(v<0 || (v==0 && k<0))
            cnt++;
        k=v;

    }
    if(v!=0)
        cout<<"-1";
    else
        cout<<cnt;
    return 0;
}


//#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <iterator>
#include <set>
#include <algorithm>
#include <cmath>
#define ll long long
using namespace std;

int main()
{
    //cout<<"Mike"<<endl;
    int n,cnt=0;
    cin>>n;
    int v;
    char c;
    cin>>c;
    if(c=='(')
    {
        v=1;
    }
    else
    {
        v=-1;
        cnt++;
    }
    for(ll i=1;i<n;i++)
    {
        cin>>c;
        if(c=='(')
        {
            v=v+1;
        }
        else
        {
            v=v-1;
        }
        if(v<0 || (v==0 && v<0))
            cnt++;

    }
    if(v!=0)
        cout<<"-1";
    else
        cout<<cnt;
    return 0;
}


//#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <iterator>
#include <set>
#include <algorithm>
#include <cmath>
#define ll long long
using namespace std;

int main()
{
    //cout<<"Mike"<<endl;
    ll n,cnt=0;
    cin>>n;
    vector<ll> v(n,0);
    char c;
    cin>>c;
    if(c=='(')
    {
        v[0]=1;
    }
    else
    {
        v[0]=-1;
        cnt++;
    }
    for(ll i=1;i<n;i++)
    {
        cin>>c;
        if(c=='(')
        {
            v[i]=v[i-1]+1;
        }
        else
        {
            v[i]=v[i-1]-1;
        }
        if(v[i]<0 || (v[i]==0 && v[i-1]<0))
            cnt++;

    }
    if(v[n-1]!=0)
        cout<<"-1";
    else
        cout<<cnt;
    return 0;
}


//#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <iterator>
#include <set>
#include <algorithm>
#include <cmath>
#define ll long long
using namespace std;

int main()
{
    //cout<<"Mike"<<endl;
    int n,cnt=0;
    cin>>n;
    vector<int> v(n,0);
    char c;
    cin>>c;
    if(c=='(')
    {
        v[0]=1;
    }
    else
    {
        v[0]=-1;
        cnt++;
    }
    for(ll i=1;i<n;i++)
    {
        cin>>c;
        if(c=='(')
        {
            v[i]=v[i-1]+1;
        }
        else
        {
            v[i]=v[i-1]-1;
        }
        if(v[i]<0 || (v[i]==0 && v[i-1]<0))
            cnt++;

    }
    if(v[n-1]!=0)
        cout<<"-1";
    else
        cout<<cnt;
    return 0;
}


#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<math.h>
#define ll long long
using namespace std;
int main()
{
    int t;
    //cin>>t;
   //for(int g=0;g<t;g++)
   {
       int n,p=0,q=0;
       cin>>n;
       string s;
       cin>>s;
       for(int i=0;i<n;i++)
        {
            if(s[i]=='(')
            p++;
            else
            q++;
        }
        if(p!=q)
        cout<<"-1"<<endl;
        else
        {
            p=0;q=0;
            for(int i=0;i<n;i++)
        {
            if(s[i]==')')
           {
               p--;
           }
           else
           p++;
             if(p<0)
           {
               q++;p=0;
           }

        }
        if(p>0 && s[n-1]=='(')
        q++;
        if(q==2)
        cout<<"2"<<endl;
        else
        cout<<2*(q)<<endl;
        }
    }
    return 0;
}


#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<math.h>
#define ll long long
using namespace std;
int main()
{
    int t;
    //cin>>t;
   //for(int g=0;g<t;g++)
   {
       int n,p=0,q=0;
       cin>>n;
       string s;
       cin>>s;
       for(int i=0;i<n;i++)
        {
            if(s[i]=='(')
            p++;
            else
            q++;
        }
        if(p!=q)
        cout<<"-1"<<endl;
        else
        {
            p=0;q=0;
            for(int i=0;i<n;i++)
        {
            if(s[i]==')')
           {
               p--;
           }
           else
          {
              p++;
          }
             if(p<0)
           {
               q++;p=0;
           }

        }
        p=0;
        for(int i=n-1;i>=0;i--)
        {
            if(s[i]=='(')
            p++;
            else
            break;
        }
        q+=p;
        if(q%2==0)
        cout<<q<<endl;
        else
        cout<<2*(q)<<endl;
        }
    }
    return 0;
}


#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<math.h>
#define ll long long
using namespace std;
int main()
{
    int t;
    //cin>>t;
   //for(int g=0;g<t;g++)
   {
       int n,p=0,q=0;
       cin>>n;
       string s;
       cin>>s;
       for(int i=0;i<n;i++)
        {
            if(s[i]=='(')
            p++;
            else
            q++;
        }
        if(p!=q)
        cout<<"-1"<<endl;
        else
        {
            p=0;q=0;
         for(int i=0;i<n;i++)
         {
		if(s[i]==')')
		p--;
		else p++;
		if(p<0||p==0&&s[i]=='(')
		q++;
         }
        cout<<(q)<<endl;
        }
    }
    return 0;
}


#include <bits/stdc++.h>
#define mod 1000000007
#define pb emplace_back
#define MP make_pair
#define dbg(x) cout << #x << ": " << x << endl
#define check(k, i, j) ((k>=i) && (k<=j))
#define ff first
#define ss second
#define all(x)  (x).begin(),(x).end()
#define rep0(i,n) for(int i=0;i<n;i++)
#define rep1(i,a,b) for(int i=a;i<b;i++)
#define FAST_IO ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
typedef long long ll;
using namespace std;
int dx[]={1,1,0,-1,-1,-1, 0, 1};
int dy[]={0,1,1, 1, 0,-1,-1,-1};

template<typename T>
void printV(vector<T> v){
    for(int i=0; i<v.size(); i++){
        cout << v[i] << " ";
    }
    cout << endl;
}

// ===================================== //

int main(){

    #ifndef ONLINE_JUDGE
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif

    FAST_IO;
    int n;
    cin >> n;
    string s;
    cin >> s;
    int l=0, r=0;
    rep0(i, s.length()){
        if(s[i]=='('){
            l++;
        }
        else{
            r++;
        }
    }
    if(l!=r){
        cout << -1 << endl;
    }
    else{
        vector<int> v(n);
        if(s[0]=='('){
            v[0]++;
        }
        else{
            v[0]--;
        }
        rep1(i, 1, n){
            if(s[i]=='('){
                v[i] = v[i-1]+1;
            }
            else{
                v[i] = v[i-1]-1;
            }
        }
        int count=0;
        int i=0;
        while(i<n){
            if(v[i]>=0){
                i++;
            }
            else{
                int j = i;
                while(j<n && v[j]<=0){
                    j++;
                }
                count+=j-i;
                i=j+1;
            }
        }
        cout << count << endl;
    }

    return 0;
}


#include <bits/stdc++.h>
#define mod 1000000007
#define pb emplace_back
#define MP make_pair
#define dbg(x) cout << #x << ": " << x << endl
#define check(k, i, j) ((k>=i) && (k<=j))
#define ff first
#define ss second
#define all(x)  (x).begin(),(x).end()
#define rep0(i,n) for(int i=0;i<n;i++)
#define rep1(i,a,b) for(int i=a;i<b;i++)
#define FAST_IO ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
typedef long long ll;
using namespace std;
int dx[]={1,1,0,-1,-1,-1, 0, 1};
int dy[]={0,1,1, 1, 0,-1,-1,-1};

template<typename T>
void printV(vector<T> v){
    for(int i=0; i<v.size(); i++){
        cout << v[i] << " ";
    }
    cout << endl;
}

// ===================================== //

int main(){

    #ifndef ONLINE_JUDGE
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif

    FAST_IO;
    int n;
    cin >> n;
    string s;
    cin >> s;
    int l=0, r=0;
    rep0(i, s.length()){
        if(s[i]=='('){
            l++;
        }
        else{
            r++;
        }
    }
    if(l!=r){
        cout << -1 << endl;
    }
    else{
        stack<char> stk;
        int i=0;
        int count=0;
        while(i<n){
            if(s[i]==')'){
                if(!stk.empty()){
                    stk.pop();
                }
                else{
                    int j=i+1;
                    int curCount=1;
                    while(j<n){
                        if(s[j]==')'){
                            curCount++;
                        }
                        else{
                            curCount--;
                        }
                        if(curCount==0){
                            count+=j-i+1;
                            break;
                        }
                        j++;
                    }
                }
            }
            else{
                stk.push('(');
            }
            i++;
        }
        cout << count << endl;
    }

    return 0;
}


#include <bits/stdc++.h>
#define mod 1000000007
#define pb emplace_back
#define MP make_pair
#define dbg(x) cout << #x << ": " << x << endl
#define check(k, i, j) ((k>=i) && (k<=j))
#define ff first
#define ss second
#define FAST_IO ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
typedef long long ll;
using namespace std;
int dx[]={1,1,0,-1,-1,-1, 0, 1};
int dy[]={0,1,1, 1, 0,-1,-1,-1};

template<typename T>
void printV(vector<T> v){
    for(int i=0; i<v.size(); i++){
        cout << v[i] << " ";
    }
    cout << endl;
}

// ===================================== //

int main(){

    #ifndef ONLINE_JUDGE
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif

    FAST_IO;
    int n;
    cin >> n;
    string s;
    cin >> s;
    int l=0, r=0;
    for(auto c: s){
        if(c=='(') l++;
        else r++;
    }
    if(l!=r || n==1){
        cout << -1 << endl;
    }
    else{
        int count=0;
        for(int i=0; i<n-1; i+=2){
            if(s[i]=='(' && s[i+1]==')'){
                continue;
            }
            else{
                count+=2;
            }
        }
        cout << count << endl;
    }

    return 0;
}


#include <bits/stdc++.h>
#define mod 1000000007
#define pb emplace_back
#define MP make_pair
#define dbg(x) cout << #x << ": " << x << endl
#define check(k, i, j) ((k>=i) && (k<=j))
#define ff first
#define ss second
#define FAST_IO ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
typedef long long ll;
using namespace std;
int dx[]={1,1,0,-1,-1,-1, 0, 1};
int dy[]={0,1,1, 1, 0,-1,-1,-1};

template<typename T>
void printV(vector<T> v){
    for(int i=0; i<v.size(); i++){
        cout << v[i] << " ";
    }
    cout << endl;
}

// ===================================== //

int main(){

    #ifndef ONLINE_JUDGE
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif

    FAST_IO;
    int n;
    cin >> n;
    string s;
    cin >> s;
    int l=0, r=0;
    for(auto c: s){
        if(c=='(') l++;
        else r++;
    }
    if(l!=r){
        cout << -1 << endl;
    }
    else{
        int count=0;
        for(int i=0; i<n-1; i+=2){
            if(s[i]=='(' && s[i+1]==')'){
                continue;
            }
            else{
                count+=2;
            }
        }
        cout << count << endl;
    }

    return 0;
}


#include <bits/stdc++.h>
using namespace std::literals::string_literals;
using i64 = std::int_fast64_t;
using std::cout;
using std::cerr;
using std::endl;
using std::cin;

template<typename T>
std::vector<T> make_v(size_t a){return std::vector<T>(a);}

template<typename T,typename... Ts>
auto make_v(size_t a,Ts... ts){
  return std::vector<decltype(make_v<T>(ts...))>(a,make_v<T>(ts...));
}

int main() {
	int n; scanf("%d", &n);
	std::string s; cin >> s;

	{
		int X = 0, Y = 0;
		for(auto c: s) {
			X += (c == '(');
			Y += (c == ')');
		}
		if(X != Y) {
			printf("-1\n");
			return 0;
		}
	}

	int ans = 0, now = 0, last = -1;
	for(int i = 0; i < n; i++) {
		if(s[i] == '(') {
			now++;
		} else if(s[i] == ')') {
			if(!now) {
				last = i;
			}
			now--;
		}
		if(!now and last != -1) {
			ans += i - last + 1;
			last = -1;
		}
	}
	if(last != -1) ans += n - last;

	printf("%d\n", ans);
	return 0;
}


#include <bits/stdc++.h>
using namespace std::literals::string_literals;
using i64 = std::int_fast64_t;
using std::cout;
using std::cerr;
using std::endl;
using std::cin;

template<typename T>
std::vector<T> make_v(size_t a){return std::vector<T>(a);}

template<typename T,typename... Ts>
auto make_v(size_t a,Ts... ts){
  return std::vector<decltype(make_v<T>(ts...))>(a,make_v<T>(ts...));
}

int main() {
	int n; scanf("%d", &n);
	std::string s; cin >> s;

	{
		int X = 0, Y = 0;
		for(auto c: s) {
			X += (c == '(');
			Y += (c == ')');
		}
		if(X != Y) {
			printf("-1\n");
			return 0;
		}
	}

	int ans = 0, tmp = 0;
	std::stack<int> st;
	for(int i = 0; i < s.size(); i++) {
		if(s[i] == '(') {
			st.push(s[i]);
			tmp++;

			if(!tmp) {
				ans += st.size();
				while(!st.empty()) st.pop();
			}
		} else {
			tmp--;

			if(!st.empty() and st.top() == '(') st.pop();
			else st.push(s[i]);
		}
	}

	printf("%d\n", ans);
	return 0;
}


#include <bits/stdc++.h>
using namespace std::literals::string_literals;
using i64 = std::int_fast64_t;
using std::cout;
using std::cerr;
using std::endl;
using std::cin;

template<typename T>
std::vector<T> make_v(size_t a){return std::vector<T>(a);}

template<typename T,typename... Ts>
auto make_v(size_t a,Ts... ts){
  return std::vector<decltype(make_v<T>(ts...))>(a,make_v<T>(ts...));
}

int main() {
	int n; scanf("%d", &n);
	std::string s; cin >> s;

	{
		int X = 0, Y = 0;
		for(auto c: s) {
			X += (c == '(');
			Y += (c == ')');
		}
		if(X != Y) {
			printf("-1\n");
			return 0;
		}
	}

	int ans = 0, tmp = 0;
	std::stack<int> st;
	for(int i = 0; i < s.size(); i++) {
		if(s[i] == '(') {
			if(!tmp) {
				ans += st.size();
				while(!st.empty()) st.pop();
			}

			st.push(s[i]);
			tmp++;
		} else {
			if(!st.empty() and st.top() == '(' and tmp > 0) {
				st.pop();
			} else {
				st.push(s[i]);
				tmp--;
			}
		}
	}
	ans += st.size();

	printf("%d\n", ans);
	return 0;
}


#include <bits/stdc++.h>
using namespace std::literals::string_literals;
using i64 = std::int_fast64_t;
using std::cout;
using std::cerr;
using std::endl;
using std::cin;

template<typename T>
std::vector<T> make_v(size_t a){return std::vector<T>(a);}

template<typename T,typename... Ts>
auto make_v(size_t a,Ts... ts){
  return std::vector<decltype(make_v<T>(ts...))>(a,make_v<T>(ts...));
}

int main() {
	int n; scanf("%d", &n);
	std::string s; cin >> s;

	{
		int X = 0, Y = 0;
		for(auto c: s) {
			X += (c == '(');
			Y += (c == ')');
		}
		if(X != Y) {
			printf("-1\n");
			return 0;
		}
	}

	int ans = 0, tmp = 0;
	std::stack<int> st;
	for(int i = 0; i < s.size(); i++) {
		if(s[i] == '(') {
			if(!tmp) {
				ans += st.size();
				while(!st.empty()) st.pop();
			}

			st.push(s[i]);
			tmp++;
		} else {
			if(!tmp) {
				ans += st.size();
				while(!st.empty()) st.pop();
			}

			if(!st.empty() and st.top() == '(') st.pop();
			else st.push(s[i]);
			tmp--;
		}
	}
	ans += st.size();

	printf("%d\n", ans);
	return 0;
}


#include <bits/stdc++.h>
using namespace std::literals::string_literals;
using i64 = std::int_fast64_t;
using std::cout;
using std::cerr;
using std::endl;
using std::cin;

template<typename T>
std::vector<T> make_v(size_t a){return std::vector<T>(a);}

template<typename T,typename... Ts>
auto make_v(size_t a,Ts... ts){
  return std::vector<decltype(make_v<T>(ts...))>(a,make_v<T>(ts...));
}

int main() {
	int n; scanf("%d", &n);
	std::string s; cin >> s;

	{
		int X = 0, Y = 0;
		for(auto c: s) {
			X += (c == '(');
			Y += (c == ')');
		}
		if(X != Y) {
			printf("-1\n");
			return 0;
		}
	}

	int ans = 0, tmp = 0;
	std::stack<int> st;
	for(int i = 0; i < s.size(); i++) {
		if(s[i] == '(') {
			if(!tmp) {
				ans += st.size();
				while(!st.empty()) st.pop();
			}

			st.push(s[i]);
			tmp++;
		} else {
			if(!st.empty() and st.top() == '(') {
				st.pop();
			} else {
				st.push(s[i]);
				tmp--;
			}
		}
	}
	ans += st.size();

	printf("%d\n", ans);
	return 0;
}


#include <bits/stdc++.h>
using namespace std::literals::string_literals;
using i64 = std::int_fast64_t;
using std::cout;
using std::cerr;
using std::endl;
using std::cin;

template<typename T>
std::vector<T> make_v(size_t a){return std::vector<T>(a);}

template<typename T,typename... Ts>
auto make_v(size_t a,Ts... ts){
  return std::vector<decltype(make_v<T>(ts...))>(a,make_v<T>(ts...));
}

int main() {
	int n; scanf("%d", &n);
	std::string s; cin >> s;

	{
		int X = 0, Y = 0;
		for(auto c: s) {
			X += (c == '(');
			Y += (c == ')');
		}
		if(X != Y) {
			printf("-1\n");
			return 0;
		}
	}

	int ans = 0, tmp = 0;
	std::stack<int> st;
	for(int i = 0; i < s.size(); i++) {
		if(s[i] == '(') {
			if(!tmp) {
				ans += st.size();
				while(!st.empty()) st.pop();
			}

			st.push(s[i]);
			tmp++;
		} else {
			tmp--;

			if(!st.empty() and st.top() == '(') st.pop();
			else st.push(s[i]);
		}
	}
	ans += st.size();

	printf("%d\n", ans);
	return 0;
}


#include <bits/stdc++.h>
using namespace std::literals::string_literals;
using i64 = std::int_fast64_t;
using std::cout;
using std::cerr;
using std::endl;
using std::cin;

template<typename T>
std::vector<T> make_v(size_t a){return std::vector<T>(a);}

template<typename T,typename... Ts>
auto make_v(size_t a,Ts... ts){
  return std::vector<decltype(make_v<T>(ts...))>(a,make_v<T>(ts...));
}

int main() {
	int n; scanf("%d", &n);
	std::string s; cin >> s;

	{
		int X = 0, Y = 0;
		for(auto c: s) {
			X += (c == '(');
			Y += (c == ')');
		}
		if(X != Y) {
			printf("-1\n");
			return 0;
		}
	}

	int ans = 0, tmp = 0;
	std::stack<int> st;
	for(int i = 0; i < s.size(); i++) {
		if(s[i] == '(') {
			if(!tmp) {
				ans += st.size();
				while(!st.empty()) st.pop();
			}

			st.push(s[i]);
			tmp++;
		} else {
			if(!tmp) {
				ans += st.size();
				while(!st.empty()) st.pop();
			}

			if(!st.empty() and st.top() == '(') {
				st.pop();
			} else {
				st.push(s[i]);
				tmp--;
			}
		}
	}
	ans += st.size();

	printf("%d\n", ans);
	return 0;
}


#include <bits/stdc++.h>
using namespace std::literals::string_literals;
using i64 = std::int_fast64_t;
using std::cout;
using std::cerr;
using std::endl;
using std::cin;

template<typename T>
std::vector<T> make_v(size_t a){return std::vector<T>(a);}

template<typename T,typename... Ts>
auto make_v(size_t a,Ts... ts){
  return std::vector<decltype(make_v<T>(ts...))>(a,make_v<T>(ts...));
}

int main() {
	int n; scanf("%d", &n);
	std::string s; cin >> s;

	{
		int X = 0, Y = 0;
		for(auto c: s) {
			X += (c == '(');
			Y += (c == ')');
		}
		if(X != Y) {
			printf("-1\n");
			return 0;
		}
	}

	int ans = 0, now = 0, last = -1;
	for(int i = 0; i < n; i++) {
		if(s[i] == '(') {
			now++;
		} else if(s[i] == ')') {
			if(!now) {
				last = i;
			}
			now--;
		}
		if(!now and last != -1) {
			ans += i - last + 1;
			last = -1;
		}
	}
	ans += n - last;

	printf("%d\n", ans);
	return 0;
}


#include <bits/stdc++.h>
#define pb push_back
#define ll long long
//   cout<<"Case #"<<t1-t<<": "<<ans<<"\n";
using namespace std;
/*bool cmp(vector<int>:: iterator it1,vector<int>:: iterator it2)
{
    if(*it1>*it2)
    return true;
    else
    return false;
}*/
/*bool cmp(int a, int b)
{
    if(abs(a)>abs(b))
    return true;
    else
    return false;
}*/
/*ll int gcd(ll int a,ll int b)
{
    if(a==0)
    return b;
    else return gcd(b%a,a);
}*/
/*bool cmp(pair<int,int> p1,pair<int,int> p2)
{
    if(p1.first<p2.first)
    return true;
    else if(p1.first==p2.first)
    {
        if(p1.second<p2.second)
        return true;
        else
        return false;
    }
    else
    return false;
}
*/
int main() {

    // For getting input from input.txt file
   //freopen("input.txt", "r", stdin);
    // Printing the Output to output.txt file
    // freopen("output.txt", "w", stdout);
  int n;
  cin>>n;
  string s;
  cin>>s;
    if(n%2)
    cout<<-1;
    else
    {
        ll int ct1=0,ct2=0,ans=0;
        for(int i=0;i<n;i++)
        {
            if(s[i]=='(')
            ct1++;
            else
            ct2++;
            if(ct1==ct2){
                if(s[i]!=')')
            ans+=ct1+ct2;
            ct1=0;
            ct2=0;

            }
        }
        cout<<ans;
    }
return 0;
}


#include <bits/stdc++.h>
#define pb push_back
#define ll long long
//   cout<<"Case #"<<t1-t<<": "<<ans<<"\n";
using namespace std;
/*bool cmp(vector<int>:: iterator it1,vector<int>:: iterator it2)
{
    if(*it1>*it2)
    return true;
    else
    return false;
}*/
/*bool cmp(int a, int b)
{
    if(abs(a)>abs(b))
    return true;
    else
    return false;
}*/
/*ll int gcd(ll int a,ll int b)
{
    if(a==0)
    return b;
    else return gcd(b%a,a);
}*/
/*bool cmp(pair<int,int> p1,pair<int,int> p2)
{
    if(p1.first<p2.first)
    return true;
    else if(p1.first==p2.first)
    {
        if(p1.second<p2.second)
        return true;
        else
        return false;
    }
    else
    return false;
}
*/
int main() {

    // For getting input from input.txt file
   //freopen("input.txt", "r", stdin);
    // Printing the Output to output.txt file
    // freopen("output.txt", "w", stdout);
  int n;
  cin>>n;
  string s;
  cin>>s;
    if(n%2)
    cout<<-1;
    else
    {
        ll int ct1=0,ct2=0,ans=0;
         for(int i=0;i<n;i++)
        {
            if(s[i]=='(')
            ct1++;
            else
            ct2++;
        }
        if(ct1!=ct2)
        cout<<-1;
        else{ct1=0,ct2=0;

        stack<char> st;
        for(int i=0;i<n;i++)
        {
            if(s[i]=='(')
            ct1++;
            else
            ct2++;
            if(st.size()==0)
            st.push(s[i]);
            else
            {
                if(s[i]==')'&&st.top()=='(')
                st.pop();
                else
                st.push(s[i]);
            }
            if(ct1==ct2){
                if(st.size())
            ans+=ct1+ct2;

            ct1=0;
            ct2=0;
            while(!st.empty())
            st.pop();
            }
        }
        cout<<ans;}
    }
return 0;
}


#include <bits/stdc++.h>
#define pb push_back
#define ll long long
//   cout<<"Case #"<<t1-t<<": "<<ans<<"\n";
using namespace std;
/*bool cmp(vector<int>:: iterator it1,vector<int>:: iterator it2)
{
    if(*it1>*it2)
    return true;
    else
    return false;
}*/
/*bool cmp(int a, int b)
{
    if(abs(a)>abs(b))
    return true;
    else
    return false;
}*/
/*ll int gcd(ll int a,ll int b)
{
    if(a==0)
    return b;
    else return gcd(b%a,a);
}*/
/*bool cmp(pair<int,int> p1,pair<int,int> p2)
{
    if(p1.first<p2.first)
    return true;
    else if(p1.first==p2.first)
    {
        if(p1.second<p2.second)
        return true;
        else
        return false;
    }
    else
    return false;
}
*/
int main() {

    // For getting input from input.txt file
   //freopen("input.txt", "r", stdin);
    // Printing the Output to output.txt file
    // freopen("output.txt", "w", stdout);
  int n;
  cin>>n;
  string s;
  cin>>s;
    if(n%2)
    cout<<-1;
    else
    {
        ll int ct1=0,ct2=0,ans=0;
        for(int i=0;i<n;i++)
        {
            if(s[i]=='(')
            ct1++;
            else
            ct2++;
        }
        if(ct1!=ct2)
        cout<<-1;
        else{ct1=0,ct2=0;
        for(int i=0;i<n;i++)
        {
            if(s[i]=='(')
            ct1++;
            else
            ct2++;
            if(ct1==ct2){
                if(s[i]!=')')
            ans+=ct1+ct2;
            ct1=0;
            ct2=0;

            }
        }
        cout<<ans;}
    }
return 0;
}


#include <bits/stdc++.h>
#define pb push_back
#define ll long long
//   cout<<"Case #"<<t1-t<<": "<<ans<<"\n";
using namespace std;
/*bool cmp(vector<int>:: iterator it1,vector<int>:: iterator it2)
{
    if(*it1>*it2)
    return true;
    else
    return false;
}*/
/*bool cmp(int a, int b)
{
    if(abs(a)>abs(b))
    return true;
    else
    return false;
}*/
/*ll int gcd(ll int a,ll int b)
{
    if(a==0)
    return b;
    else return gcd(b%a,a);
}*/
/*bool cmp(pair<int,int> p1,pair<int,int> p2)
{
    if(p1.first<p2.first)
    return true;
    else if(p1.first==p2.first)
    {
        if(p1.second<p2.second)
        return true;
        else
        return false;
    }
    else
    return false;
}
*/
int main() {

    // For getting input from input.txt file
   //freopen("input.txt", "r", stdin);
    // Printing the Output to output.txt file
    // freopen("output.txt", "w", stdout);
  int n;
  cin>>n;
  string s;
  cin>>s;
    if(n%2)
    cout<<-1;
    else
    {   stack<char> st;
        ll int ct1=0,ct2=0,ans=0;
        for(int i=0;i<n;i++)
        {
            if(s[i]=='(')
            ct1++;
            else
            ct2++;
            if(st.size()==0)
            st.push(s[i]);
            else
            {
                if(s[i]==')'&&st.top()=='(')
                st.pop();
                else
                st.push(s[i]);
            }
            if(ct1==ct2){
                if(st.size())
            ans+=ct1+ct2;

            ct1=0;
            ct2=0;
            while(!st.empty())
            st.pop();
            }
        }
        cout<<ans;
    }
return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{ios_base::sync_with_stdio(false);
cin.tie(NULL);
long int t,i,j=0,k=0,d=0;
cin>>t;
string a;
cin>>a;
if(t%2!=0)
{cout<<-1;}
else
{
	for(i=0;i<t;i++)
	{
	   if(a[i]=='(')
	   {
	   	if(j>k){d+=2;}
	   	k+=1;
	   }
	if(a[i]==')')
	{j+=1;}

	}
  cout<<d;
}
return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{ios_base::sync_with_stdio(false);
cin.tie(NULL);
long int t,i,j=0;
cin>>t;
string a;
cin>>a;
if(t%2!=0)
{cout<<-1;}
else
{
	for(i=0;i<t-1;i+=2)
	{  	if(a[i] == '(' and a[i+1]==')'){continue;}
		if(a[i] == '(' and a[i+1]=='('){j=j+2;}
		if(a[i] == ')' and a[i+1]=='('){j=j+2;}
		if(a[i] == ')' and a[i+1]==')'){j=j+2;}

	}
  cout<<j;
}
return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{ios_base::sync_with_stdio(false);
cin.tie(NULL);
long int t,i,j=0,k=0,d=0;
cin>>t;
string a;
cin>>a;
	for(i=0;i<t;i++)
	{
	   if(a[i]=='(')
	   {
	   	if(j>k){d+=2;}
	   	k+=1;
	   }
	if(a[i]==')')
	{j+=1;}

	}
	if(j!=k){cout<<-1;
	}
	else{cout<<d;}
return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{ios_base::sync_with_stdio(false);
cin.tie(NULL);
long int t,i,j=0;
cin>>t;
string a;
cin>>a;
if(t%2!=0)
{cout<<-1;}
else
{
	for(i=0;i<t-1;i+=2)
	{
		if(a[i] == '(' and a[i+1]==')'){continue;}
		else{j=j+2;}
	}
  cout<<j;
}
return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<ll> vi;
typedef vector<bool> vb;
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define sq(x) ((x)*(x))
#define fo(i,n) for(int i=0;i<n;i++)
#define fp(i,k,n) for(int i=k;i<n;i++)
#define Fo(i,n) for(int i=1;i<=n;i++)
#define all(x) x.begin(),x.end()
#define deb(x) cout<<#x<<"="<<x<<"\n"
#define deb2(x,y) cout<<#x<<"="<<x<<" "<<#y<<"="<<y<<"\n"
#define fi first
#define se second
const double pi = 3.14159265358979323846;
#define uni(c) (c).resize(unique(all(c))-(c).begin())
#define fast ios_base::sync_with_stdio(0);cin.tie(NULL)
//pair <int, int> w[4] = {mp(-1, 0), mp(0, -1), mp(1, 0), mp(0, 1)};   // for matrix movement:
void cp()
{
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif // ONLINE_JUDGE
}
void solve()
{
    ll n; cin >> n;
    string s; cin >> s;
    if (n % 2)
    {
        cout << "-1";
        return;
    }
    ll c = 0;
    for (char p : s)
        if (p == '(')
            c++;
    if (c != n / 2) {
        cout << "-1";
        return;
    }
    c = 0;
    ll ans = 0, p = 0;
    for (int i = 0; i < n; ++i)
    {
        if (c == 0 and s[i] == ')')
            p = i;
        if (c == -1 and s[i] == '(')
            ans += i - p + 1;
        c += s[i] == '(' ? 1 : -1;
    }
    cout << ans;

}
int main()
{
    fast;
    //cp();
    ll t = 1;
    //cin >> t;
    while (t--)
        solve();

    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

int a,n;
char s[4001];
int num[4001],sum[4001];
long long ans;
int h[40001];

long long calc(int x)
{
	long long ss=0;
	h[0]++; if (x>sum[n]) return 0;
	for (int i=1;i<=n;i++)
	{
		if (sum[i]-x>=0) ss+=h[sum[i]-x];
		h[sum[i]]++;
	}
	for (int i=0;i<=n;i++) h[sum[i]]=0;
	return ss;
}

int main()
{
	scanf("%d",&a);
	scanf("%s",s+1); n=strlen(s+1);
	for (int i=1;i<=n;i++) num[i]=s[i]-'0',sum[i]=sum[i-1]+num[i];
	if (a==0)
	{
		printf("%I64d\n",2ll*calc(0)*n*(n+1)/2-calc(0)*calc(0));
		return 0;
	}
	for (int i=1;i<=a/i;i++)
		if (a%i==0)
		{
			if (i!=a/i) { ans+=2ll*calc(i)*calc(a/i);if (a==20593444) printf("%d %d %I64d\n",i,a/i,ans); }
			else {  ans+=1ll*calc(i)*calc(i); if (a==20593444) printf("%d %I64d\n",i,ans); }
		}
	printf("%I64d\n",ans);
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

int a,n;
char s[4001];
int num[4001],sum[4001];
long long ans;
int h[40001];

long long calc(int x)
{
	long long ans=0;
	h[0]++; if (x>sum[n]) return 0;
	for (int i=1;i<=n;i++)
	{
		if (sum[i]-x>=0) ans+=h[sum[i]-x];
		h[sum[i]]++;
	}
	for (int i=0;i<=n;i++) h[sum[i]]=0;
	return ans;
}

int main()
{
	scanf("%d",&a);
	scanf("%s",s+1); n=strlen(s+1);
	for (int i=1;i<=n;i++) num[i]=s[i]-'0',sum[i]=sum[i-1]+num[i];

	if (a==0)
	{
		printf("%I64d\n",2ll*calc(0)*n*(n+1)/2-calc(0)*calc(0));
		return 0;
	}
	for (int i=1;i<=a/i;i++)
		if (a%i==0)
		{
			if (i!=a/i) { ans+=2ll*calc(i)*calc(a/i); }
			else { ans+=1ll*calc(i)*calc(i); }
			if (a==20593444&&ans!=0) printf("%d %d %d %I64d\n",i,a/i,ans,calc(4538));
		}
	printf("%I64d\n",ans);
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

int a,n;
char s[10001];
int num[10001],sum[10001];
long long ans;
int h[400001];

long long calc(int x)
{
    long long ss=0;
    h[0]++; if (x>sum[n]) return 0;
    for (int i=1;i<=n;i++)
    {
        if (sum[i]-x>=0) ss+=h[sum[i]-x];
        h[sum[i]]++;
    }
    for (int i=0;i<=n;i++) h[sum[i]]=0;
    return ss;
}

int main()
{
    scanf("%d",&a);
    scanf("%s",s+1); n=strlen(s+1);
    for (int i=1;i<=n;i++) num[i]=s[i]-'0',sum[i]=sum[i-1]+num[i];
    if (a==0)
    {
        printf("%I64d\n",2ll*calc(0)*n*(n+1)/2-calc(0)*calc(0));
        return 0;
    }
    for (int i=1;i<=a/i;i++)
        if (a%i==0)
        {
            if (i!=a/i) { ans+=2ll*calc(i)*calc(a/i);}
            else {
                long long t=calc(i);
            /*  if (a==20593444)
                {
                //  printf("%d %I64d %I64d\n",i,calc(i)*calc(i),ans);
                    long long t=calc(i);
                    if (((t*t+ans)==2)&&(t*t==1)&&(ans==0)) printf("hahahaha\n");
                }*/
                if (a==20593444) printf("%I64d %I64d\n",t,calc(i));
                ans=(ans+t*t);
            }
        }
    printf("%I64d\n",ans);
}


#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <memory.h>
#include <vector>
#include <iomanip>
#include <string>
#include <list>
#include <map>
#include <set>
#include <ctime>
#include <functional>
#include <bitset>

#define pb push_back
#define mk make_pair
#define sqr(N) ((N)*(N))
#define F first
#define S second
#define maxn 101010

using namespace std;

typedef long long ll;

string s;

int a, i, j, k, mx = 0, f[44444];
int cnt[444444], ans[4444];

int main(){
#ifndef ONLINE_JUDGE
 freopen("input.txt", "r", stdin);
 freopen("output.txt", "w", stdout);
#endif
  cin >> a >> s;
  int k = s.size();
  for(i = 0; i < k; i++)f[i + 1] = s[i] - 48;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
    cnt[sum]++;
    mx = max(mx, sum);
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      mx = max(mx, sum);
      cnt[sum]++;
    }
  }
  long long ans = 0;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
   if(sum != 0 && a % sum == 0 && a / sum <= mx)ans += cnt[a / sum];
   else if(sum == 0 && a == 0)ans += cnt[0];
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      if(sum != 0 && a % sum == 0 && a / sum <= mx)ans += cnt[a / sum];
      else if(sum == 0 && a == 0)ans += cnt[0];
    }
  }
  if(a > 1)
    for(j = 1; j <= k; j++)if(f[j] * f[j] == a)ans++;
  cout << ans << endl;
  return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <memory.h>
#include <vector>
#include <iomanip>
#include <string>
#include <list>
#include <map>
#include <set>
#include <ctime>
#include <functional>
#include <bitset>

#define pb push_back
#define mk make_pair
#define sqr(N) ((N)*(N))
#define F first
#define S second
#define maxn 101010

using namespace std;

typedef long long ll;

string s;

int a, i, j, k, mx = 0, f[44444], cnt[444444];

int main(){
#ifndef ONLINE_JUDGE
 freopen("input.txt", "r", stdin);
 freopen("output.txt", "w", stdout);
#endif
  cin >> a >> s;
  int k = s.size();
  for(i = 0; i < k; i++)f[i + 1] = s[i] - 48;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
    cnt[sum]++;
    mx = max(mx, sum);
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      mx = max(mx, sum);
      cnt[sum]++;
    }
  }
  ll ans = 0;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
    if(a % sum == 0 && a / sum <= mx)ans += cnt[a / sum];
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      if(a % sum == 0 && a / sum <= mx)ans += cnt[a / sum];
    }
  }
  cout << ans << endl;
  return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <memory.h>
#include <vector>
#include <iomanip>
#include <string>
#include <list>
#include <map>
#include <set>
#include <ctime>
#include <functional>
#include <bitset>

#define pb push_back
#define mk make_pair
#define sqr(N) ((N)*(N))
#define F first
#define S second
#define maxn 101010

using namespace std;

typedef long long ll;

string s;

int a, i, j, k, mx = 0, f[44444];
int cnt[444444], ans[4444];

int main(){
#ifndef ONLINE_JUDGE
 freopen("input.txt", "r", stdin);
 freopen("output.txt", "w", stdout);
#endif
  cin >> a >> s;
  int k = s.size();
  for(i = 0; i < k; i++)f[i + 1] = s[i] - 48;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
    cnt[sum]++;
    mx = max(mx, sum);
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      mx = max(mx, sum);
      cnt[sum]++;
    }
  }
  long long ans = 0;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
   if(sum != 0 && a % sum == 0 && a / sum <= mx){
     ans += cnt[a / sum];
   }
   else if(sum == 0 && a == 0)ans += cnt[0];
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      if(sum != 0 && a % sum == 0 && a / sum <= mx){
        ans += cnt[a / sum];
      }
      else if(sum == 0 && a == 0)ans += cnt[0];
    }
  }
  if(a > 1)
  for(i = 1; i <= k; i++)
    for(j = 1; j <= k; j++)if(f[i] * f[j] == a)ans++;
  cout << ans << endl;
  return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <memory.h>
#include <vector>
#include <iomanip>
#include <string>
#include <list>
#include <map>
#include <set>
#include <ctime>
#include <functional>
#include <bitset>

#define pb push_back
#define mk make_pair
#define sqr(N) ((N)*(N))
#define F first
#define S second
#define maxn 101010

using namespace std;

typedef long long ll;

string s;

int a, i, j, k, mx = 0, f[44444];
int cnt[444444], ans[4444];

int main(){
#ifndef ONLINE_JUDGE
 freopen("input.txt", "r", stdin);
 freopen("output.txt", "w", stdout);
#endif
  cin >> a >> s;
  int k = s.size();
  for(i = 0; i < k; i++)f[i + 1] = s[i] - 48;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
    cnt[sum]++;
    mx = max(mx, sum);
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      mx = max(mx, sum);
      cnt[sum]++;
    }
  }
  long long ans = 0;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
   if(sum != 0 && a % sum == 0 && a / sum <= mx){
	 if(a == sum)ans += cnt[sum];
	 ans += cnt[a / sum];
   }
   else if(sum == 0 && a == 0)ans += cnt[0];
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      if(sum != 0 && a % sum == 0 && a / sum <= mx){
	    ans += cnt[a / sum];
	    if(a == sum)ans += cnt[sum];
	  }
	  else if(sum == 0 && a == 0)ans += cnt[0];
    }
  }
  cout << ans << endl;
  return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <memory.h>
#include <vector>
#include <iomanip>
#include <string>
#include <list>
#include <map>
#include <set>
#include <ctime>
#include <functional>
#include <bitset>

#define pb push_back
#define mk make_pair
#define sqr(N) ((N)*(N))
#define F first
#define S second
#define maxn 101010

using namespace std;

typedef long long ll;

string s;

int a, i, j, k, mx = 0, f[44444];
int cnt[444444], ans[4444];

int main(){
#ifndef ONLINE_JUDGE
 freopen("input.txt", "r", stdin);
 freopen("output.txt", "w", stdout);
#endif
  cin >> a >> s;
  int k = s.size();
  for(i = 0; i < k; i++)f[i + 1] = s[i] - 48;
  int cnt1 = 0;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
    cnt[sum]++;
    cnt1++;
    mx = max(mx, sum);
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      mx = max(mx, sum);
      cnt[sum]++;
      cnt1++;
    }
  }
  long long ans = 0;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];

   if(sum != 0 && a % sum == 0 && a / sum <= mx){
     ans += cnt[a / sum];
   }
   else if(sum == 0 && a == 0)ans += cnt1;
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      if(sum != 0 && a % sum == 0 && a / sum <= mx){
        ans += cnt[a / sum];
      }
      else if(sum == 0 && a == 0)ans += cnt1;
    }
  }
  cout << ans << endl;
  return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <memory.h>
#include <vector>
#include <iomanip>
#include <string>
#include <list>
#include <map>
#include <set>
#include <ctime>
#include <functional>
#include <bitset>

#define pb push_back
#define mk make_pair
#define sqr(N) ((N)*(N))
#define F first
#define S second
#define maxn 101010

using namespace std;

typedef long long ll;

char c[44444];
string s;

int a, i, j, k, mx = 0, f[44444], cnt[444444];

int main(){
#ifndef ONLINE_JUDGE
 freopen("input.txt", "r", stdin);
 freopen("output.txt", "w", stdout);
#endif
  scanf("%d", &a);
  scanf("%s", &c);
  s = c;
  int k = s.size();
  for(i = 0; i < k; i++)f[i + 1] = s[i] - 48;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
    cnt[sum]++;
    mx = max(mx, sum);
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      mx = max(mx, sum);
      cnt[sum]++;
    }
  }
  ll ans = 0;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
    if(a % sum == 0 && a / sum <= mx)ans += cnt[a / sum];
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      if(a % sum == 0 && a / sum <= mx)ans += cnt[a / sum];
    }
  }
  cout << ans << endl;
  return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <memory.h>
#include <vector>
#include <iomanip>
#include <string>
#include <list>
#include <map>
#include <set>
#include <ctime>
#include <functional>
#include <bitset>

#define pb push_back
#define mk make_pair
#define sqr(N) ((N)*(N))
#define F first
#define S second
#define maxn 101010

using namespace std;

typedef long long ll;

string s;

int a, i, j, k, mx = 0, f[44444];
int cnt[444444], ans[4444];

int main(){
#ifndef ONLINE_JUDGE
 freopen("input.txt", "r", stdin);
 freopen("output.txt", "w", stdout);
#endif
  cin >> a >> s;
  int k = s.size();
  for(i = 0; i < k; i++)f[i + 1] = s[i] - 48;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
    cnt[sum]++;
    mx = max(mx, sum);
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      mx = max(mx, sum);
      cnt[sum]++;
    }
  }
  long long ans = 0;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
   if(sum != 0 && a % sum == 0 && a / sum <= mx){
     if(a == sum)ans += cnt[sum];
     else ans += cnt[a / sum];
   }
   else if(sum == 0 && a == 0)ans += cnt[0];
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      if(sum != 0 && a % sum == 0 && a / sum <= mx){
        if(a == sum)ans += cnt[sum];
        else ans += cnt[a / sum];
      }
      else if(sum == 0 && a == 0)ans += cnt[0];
    }
  }
  cout << ans << endl;
  return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <memory.h>
#include <vector>
#include <iomanip>
#include <string>
#include <list>
#include <map>
#include <set>
#include <ctime>
#include <functional>
#include <bitset>

#define pb push_back
#define mk make_pair
#define sqr(N) ((N)*(N))
#define F first
#define S second
#define maxn 101010

using namespace std;

typedef long long ll;

string s;

int a, i, j, k, mx = 0, f[44444];
int cnt[444444], ans[4444];

int main(){
#ifndef ONLINE_JUDGE
 freopen("input.txt", "r", stdin);
 freopen("output.txt", "w", stdout);
#endif
  cin >> a >> s;
  int k = s.size();
  for(i = 0; i < k; i++)f[i + 1] = s[i] - 48;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
    cnt[sum]++;
    mx = max(mx, sum);
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      mx = max(mx, sum);
      cnt[sum]++;
    }
  }
  long long ans = 0;
  if(k == 1 && f[1] == a)ans = 1;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
   if(sum != 0 && a % sum == 0 && a / sum <= mx){
     ans += cnt[a / sum];
   }
   else if(sum == 0 && a == 0)ans += cnt[0];
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      if(sum != 0 && a % sum == 0 && a / sum <= mx){
        ans += cnt[a / sum];
      }
      else if(sum == 0 && a == 0)ans += cnt[0];
    }
  }
  cout << ans << endl;
  return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <memory.h>
#include <vector>
#include <iomanip>
#include <string>
#include <list>
#include <map>
#include <set>
#include <ctime>
#include <functional>
#include <bitset>

#define pb push_back
#define mk make_pair
#define sqr(N) ((N)*(N))
#define F first
#define S second
#define maxn 101010

using namespace std;

typedef long long ll;

string s;

int a, i, j, k, mx = 0, f[44444];
int cnt[444444], ans[4444];

int main(){
#ifndef ONLINE_JUDGE
 freopen("input.txt", "r", stdin);
 freopen("output.txt", "w", stdout);
#endif
  cin >> a >> s;
  int k = s.size();
  for(i = 0; i < k; i++)f[i + 1] = s[i] - 48;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
    cnt[sum]++;
    mx = max(mx, sum);
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      mx = max(mx, sum);
      cnt[sum]++;
    }
  }
  unsigned long long ans = 0;
  for(i = 1; i <= k; i++){
    int sum = 0, h;
    for(j = 1; j <= i; j++)sum += f[j];
	if(sum != 0 && a % sum == 0 && a / sum <= mx)ans += cnt[a / sum];
	else if(sum == 0 && a == 0)ans += cnt[0];
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      if(sum != 0 && a % sum == 0 && a / sum <= mx)ans += cnt[a / sum];
	  else if(sum == 0 && a == 0)ans += cnt[0];
	}
  }
  cout << ans << endl;
  return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <memory.h>
#include <vector>
#include <iomanip>
#include <string>
#include <list>
#include <map>
#include <set>
#include <ctime>
#include <functional>
#include <bitset>

#define pb push_back
#define mk make_pair
#define sqr(N) ((N)*(N))
#define F first
#define S second
#define maxn 101010

using namespace std;

typedef long long ll;

string s;

int a, i, j, k, mx = 0, f[44444];
int cnt[444444], ans[4444];

int main(){
#ifndef ONLINE_JUDGE
 freopen("input.txt", "r", stdin);
 freopen("output.txt", "w", stdout);
#endif
  cin >> a >> s;
  int k = s.size();
  for(i = 0; i < k; i++)f[i + 1] = s[i] - 48;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
    cnt[sum]++;
    mx = max(mx, sum);
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      mx = max(mx, sum);
      cnt[sum]++;
    }
  }
  long long ans = 0;
  for(i = 1; i <= k; i++){
    int sum = 0;
    for(j = 1; j <= i; j++)sum += f[j];
   if(sum != 0 && a % sum == 0 && a / sum <= mx){
     if(a == sum && i == 1)ans += cnt[sum];
     ans += cnt[a / sum];
   }
   else if(sum == 0 && a == 0)ans += cnt[0];
    for(j = i + 1; j <= k; j++){
      sum -= f[j - i];
      sum += f[j];
      if(sum != 0 && a % sum == 0 && a / sum <= mx){
        if(a == sum && i == 1)ans += cnt[sum];
        ans += cnt[a / sum];
      }
      else if(sum == 0 && a == 0)ans += cnt[0];
    }
  }
  cout << ans << endl;
  return 0;
}


#include <iostream>
#include <string>
#include <map>
using namespace std;
int main(){
	int A;
	cin >> A;
	string B;
	cin >> B;
	for(int i=0;i<B.size();i++)
		B[i]-='0';
	if(A==0){
		long long sifir=0;
		int array[B.size()+1];
		fill(array,array+B.size()+1,0);//ilk rakam 1 son rakam bnin sizeı
		for(int i=1;i<=B.size();i++)
			array[i]=array[i-1]+B[i-1];
		for(int i=0;i<B.size();i++){
			for(int j=i+1;j<=B.size();j++){
				if(array[j]-array[i]==0){
					sifir++;
				}
			}
		}
		long long result=B.size()*(B.size()+1)/2-sifir;
		result=result*sifir*2+sifir*sifir;
		cout << result << endl;
		return 0;
	}
	map<int,int> mp,mp1;
	for(int j=1;j*j<=A;j++){
		if(A%j==0)
			mp[j]=1;
	}
	for(map<int,int>::iterator it=mp.begin();it!=mp.end();it++){
		if(A/it->first==it->first)
			continue;
		mp1[A/it->first]=1;
	}
	mp.insert(mp1.begin(),mp1.end());
	mp1.clear();
	map<int,pair<int,int> >mp2;
	int array[B.size()+1];
	fill(array,array+B.size()+1,0);//ilk rakam 1 son rakam bnin sizeı
	for(int i=1;i<=B.size();i++)
		array[i]=array[i-1]+B[i-1];
	for(int i=0;i<B.size();i++){
		for(int j=i+1;j<=B.size();j++){
			if(mp.find(array[j]-array[i])!=mp.end()){
				//cout << array[j]-array[i] << endl;
				if((array[j]-array[i])<=A/(array[j]-array[i])){
					mp2[min(A/(array[j]-array[i]),(array[j]-array[i]))].first++;
				}
				else{
					mp2[min(A/(array[j]-array[i]),(array[j]-array[i]))].second++;
				}
			}
		}
	}
	map<int,pair<int,int> >::iterator it;
	long long sum=0;
	for(it=mp2.begin();it!=mp2.end();it++){
		//cout << it->first << " " << it->second.first << " " << it->second.second << endl;
		if(it->first*it->first==A){
			sum+=(it->second.first*(it->second.first));
		}
		else{
			sum+=it->second.first*it->second.second*2;
		}
	}
	cout << sum << endl;
	return 0;
}


#include <iostream>
#include <string>
#include <map>
using namespace std;
int main(){
	int A;
	cin >> A;
	string B;
	cin >> B;
	for(int i=0;i<B.size();i++)
		B[i]-='0';
	map<int,int> mp,mp1;
	for(int j=1;j*j<=A;j++){
		if(A%j==0)
			mp[j]=1;
	}
	for(map<int,int>::iterator it=mp.begin();it!=mp.end();it++){
		if(A/it->first==it->first)
			continue;
		mp1[A/it->first]=1;
	}
	mp.insert(mp1.begin(),mp1.end());
	mp1.clear();
	map<int,pair<int,int> >mp2;
	int array[B.size()+1];
	fill(array,array+B.size()+1,0);//ilk rakam 1 son rakam bnin sizeı
	for(int i=1;i<=B.size();i++)
		array[i]=array[i-1]+B[i-1];
	for(int i=0;i<B.size();i++){
		for(int j=i+1;j<=B.size();j++){
			if(mp.find(array[j]-array[i])!=mp.end()){
				cout << array[j]-array[i] << endl;
				if((array[j]-array[i])<=A/(array[j]-array[i])){
					mp2[min(A/(array[j]-array[i]),(array[j]-array[i]))].first++;
				}
				else{
					mp2[min(A/(array[j]-array[i]),(array[j]-array[i]))].second++;
				}
			}
		}
	}
	map<int,pair<int,int> >::iterator it;
	int sum=0;
	for(it=mp2.begin();it!=mp2.end();it++){
		cout << it->first << " " << it->second.first << " " << it->second.second << endl;
		if(it->first*it->first==A){
			sum+=(it->second.first*(it->second.first));
		}
		else{
			sum+=it->second.first*it->second.second*2;
		}
	}
	cout << sum << endl;
	return 0;
}


#include <iostream>
#include <string>
#include <map>
using namespace std;
int main(){
	int A;
	cin >> A;
	string B;
	cin >> B;
	for(int i=0;i<B.size();i++)
		B[i]-='0';
	map<int,int> mp,mp1;
	for(int j=1;j*j<=A;j++){
		if(A%j==0)
			mp[j]=1;
	}
	for(map<int,int>::iterator it=mp.begin();it!=mp.end();it++){
		if(A/it->first==it->first)
			continue;
		mp1[A/it->first]=1;
	}
	mp.insert(mp1.begin(),mp1.end());
	mp1.clear();
	map<int,pair<int,int> >mp2;
	int array[B.size()+1];
	fill(array,array+B.size()+1,0);//ilk rakam 1 son rakam bnin sizeı
	for(int i=1;i<=B.size();i++)
		array[i]=array[i-1]+B[i-1];
	for(int i=0;i<B.size();i++){
		for(int j=i+1;j<=B.size();j++){
			if(mp.find(array[j]-array[i])!=mp.end()){
				//cout << array[j]-array[i] << endl;
				if((array[j]-array[i])<=A/(array[j]-array[i])){
					mp2[min(A/(array[j]-array[i]),(array[j]-array[i]))].first++;
				}
				else{
					mp2[min(A/(array[j]-array[i]),(array[j]-array[i]))].second++;
				}
			}
		}
	}
	map<int,pair<int,int> >::iterator it;
	int sum=0;
	for(it=mp2.begin();it!=mp2.end();it++){
		//cout << it->first << " " << it->second.first << " " << it->second.second << endl;
		if(it->first*it->first==A){
			sum+=(it->second.first*(it->second.first));
		}
		else{
			sum+=it->second.first*it->second.second*2;
		}
	}
	cout << sum << endl;
	return 0;
}