#include <bits/stdc++.h>
#define ll long long int
#define pb push_back
#define st first
#define nd second
#define pii pair<int,int>
#define mp make_pair

using namespace std;

const int nax = 5e5 + 5;

char s[nax];

ll dp[nax];

int nxt1[nax];

ll ans = 0;

const int roz = (1<<20);
int tree[roz];
void dodaj(int pos,int val)
{
    pos += roz/2;
    tree[pos] = val;
    pos /= 2;
    while(pos >= 1)
    {
        tree[pos] = max(tree[pos*2],tree[pos*2+1]);
        pos >>= 1;
    }
    return;
}

int ask(int x,int y,int z,int lo,int hi)
{
        hi--;
        lo += roz/2;
        hi += roz/2;
        if(lo > hi) return -1e9;
        int res = tree[lo];
        if(lo != hi) res = max(res,tree[hi]);
        while((lo>>1) != (hi>>1))
        {
            if((lo&1) == 0) res = max(res,tree[lo+1]);
            if(hi&1) res = max(res,tree[hi-1]);
            lo >>= 1;
            hi >>= 1;
        }
        return res;
}

int main()
{
    ios_base::sync_with_stdio(0); cin.tie(0);

    int n; cin>>n;
    string x; cin>>x;
    for(int i=1;i<=n;i++) s[i] = x[i-1];

    nxt1[n + 1] = n+1;
    for(int i=n;i>=1;i--)
    {
        if(s[i] == '1') nxt1[i] = i;
        else nxt1[i] = nxt1[i+1];
    }

    ll sz = 0;

    for(int i=n;i>=1;i--)
    {
        if(s[i] == '0')
        {
            if(i < n && s[i+1] == '1') dodaj(i + 1,sz);
            int idx = nxt1[i];
            dp[i] = dp[idx];
            sz = 0;
            continue;
        }

        sz++;

        dp[i] += (sz) * (sz + 1) / 2;

        int LO = i + 1;
        int HI = n;
        int pos;
        if(ask(0,roz/2,1,LO,HI+1) <= sz)
        {
            pos = n + 1;
        }
        else
        {
            while(LO + 1 < HI)
            {
                int mid = (LO + HI) / 2;
                if(ask(0,roz/2,1,LO,mid+1) > sz)
                {
                    HI = mid;
                }
                else LO = mid;
            }

            if(ask(0,roz/2,1,LO,LO+1)) pos = LO;
            else pos = HI;
        }

        if(pos == n + 1)
        {
            ll ile = (n - i + 1);
            ile -= sz;
            dp[i] += ile * sz;
            continue;
        }

        ll done = (i + sz - 1);
        dp[i] += (ll)(pos - done - 1) * sz;
        dp[i] += dp[pos];
        dp[i] += (sz * (sz-1) / 2);

    }

    for(int i=1;i<=n;i++) ans += dp[i];
    cout<<ans;

    return 0;
}


#include <bits/stdc++.h>
#define ll long long int
#define pb push_back
#define st first
#define nd second
#define pii pair<int,int>
#define mp make_pair

using namespace std;

const int nax = 5e5 + 5;

char s[nax];

ll dp[nax];

int nxt1[nax];

ll ans = 0;

const int roz = (1<<20);
int tree[roz];
void dodaj(int pos,int val)
{
    pos += roz/2;
    tree[pos] = val;
    pos /= 2;
    while(pos >= 1)
    {
        tree[pos] = max(tree[pos*2],tree[pos*2+1]);
        pos >>= 1;
    }
    return;
}

int ask(int lo,int hi,int u,int a,int b)
{
    if(lo == a && b == hi) return tree[u];
    if(b<=a) return -1e9;
    int mid =(lo+hi)>>1;
    int l = ask(lo,mid,u*2,a,min(b,mid));
    int r = ask(mid,hi,u*2+1,max(a,mid),b);
    return max(l,r);
}

int main()
{
    ios_base::sync_with_stdio(0); cin.tie(0);

    int n; cin>>n;
    string x; cin>>x;
    for(int i=1;i<=n;i++) s[i] = x[i-1];

    nxt1[n + 1] = n+1;
    for(int i=n;i>=1;i--)
    {
        if(s[i] == '1') nxt1[i] = i;
        else nxt1[i] = nxt1[i+1];
    }

    ll sz = 0;

    for(int i=n;i>=1;i--)
    {
        if(s[i] == '0')
        {
            if(i < n && s[i+1] == '1') dodaj(i + 1,sz);
            int idx = nxt1[i];
            dp[i] = dp[idx];
            sz = 0;
            continue;
        }

        sz++;

        dp[i] += (sz) * (sz + 1) / 2;

        int LO = i + 1;
        int HI = n;
        int pos;
        if(ask(0,roz/2,1,LO,HI+1) <= sz)
        {
            pos = n + 1;
        }
        else
        {
            while(LO + 1 < HI)
            {
                int mid = (LO + HI) / 2;
                if(ask(0,roz/2,1,LO,mid+1) > sz)
                {
                    HI = mid;
                }
                else LO = mid;
            }

            if(ask(0,roz/2,1,LO,LO+1)) pos = LO;
            else pos = HI;
        }

        if(pos == n + 1)
        {
            ll ile = (n - i + 1);
            ile -= sz;
            dp[i] += ile * sz;
            continue;
        }

        ll done = (i + sz - 1);
        dp[i] += (ll)(pos - done - 1) * sz;
        dp[i] += dp[pos];
        dp[i] += (sz * (sz-1) / 2);

    }

    for(int i=1;i<=n;i++) ans += dp[i];
    cout<<ans;

    return 0;
}


#include <bits/stdc++.h>
#define ll long long int
#define pb push_back
#define st first
#define nd second
#define pii pair<int,int>
#define mp make_pair

using namespace std;

const int nax = 5e5 + 5;

char s[nax];

ll dp[nax];

int nxt1[nax];

ll ans = 0;

const int roz = (1<<20);
int tree[roz];
void dodaj(int pos,int val)
{
    pos += roz/2;
    tree[pos] = val;
    pos /= 2;
    while(pos >= 1)
    {
        tree[pos] = max(tree[pos*2],tree[pos*2+1]);
        pos >>= 1;
    }
    return;
}

int ask(int lo,int hi,int u,int a,int b)
{
    if(lo == a && b == hi) return tree[u];
    if(b<=a) return -1e9;
    int mid =(lo+hi)/2;
    int l = ask(lo,mid,u*2,a,min(b,mid));
    int r = ask(mid,hi,u*2+1,max(a,mid),b);
    return max(l,r);
}

int main()
{
    ios_base::sync_with_stdio(0); cin.tie(0);

    int n; cin>>n;
    string x; cin>>x;
    for(int i=1;i<=n;i++) s[i] = x[i-1];

    nxt1[n + 1] = n+1;
    for(int i=n;i>=1;i--)
    {
        if(s[i] == '1') nxt1[i] = i;
        else nxt1[i] = nxt1[i+1];
    }

    ll sz = 0;

    for(int i=n;i>=1;i--)
    {
        if(s[i] == '0')
        {
            if(i < n && s[i+1] == '1') dodaj(i + 1,sz);
            int idx = nxt1[i];
            dp[i] = dp[idx];
            sz = 0;
            continue;
        }

        sz++;

        dp[i] += (sz) * (sz + 1) / 2;

        int LO = i + 1;
        int HI = n;
        int pos;
        if(ask(0,roz/2,1,LO,HI+1) <= sz)
        {
            pos = n + 1;
        }
        else
        {
            while(LO + 1 < HI)
            {
                int mid = (LO + HI) / 2;
                if(ask(0,roz/2,1,LO,mid+1) > sz)
                {
                    HI = mid;
                }
                else LO = mid;
            }

            if(ask(0,roz/2,1,LO,LO+1)) pos = LO;
            else pos = HI;
        }

        if(pos == n + 1)
        {
            ll ile = (n - i + 1);
            ile -= sz;
            dp[i] += ile * sz;
            continue;
        }

        ll done = (i + sz - 1);
        dp[i] += (ll)(pos - done - 1) * sz;
        dp[i] += dp[pos];
        dp[i] += (sz * (sz-1) / 2);

    }

    for(int i=1;i<=n;i++) ans += dp[i];
    cout<<ans;

    return 0;
}


#include <iostream>
#include <vector>
#include <list>
#include <math.h>
#include <bits/stdc++.h>
using namespace std;
#define mp make_pair
typedef long long int ll;
#define pb push_back
vector <pair<ll,ll> > lr;
vector <ll> dp;
int main()
{
    int n; cin >> n;
    int l = 1; int leng = 0;
    for(int i = 1; i <= n; i++)
    {
        char e; cin >> e;
        if(e == '1'){leng ++;}
        if(e=='0' || i == n)
        {
            if(leng > 0)
            {

                leng = 0;
                lr.pb(mp(l , i - (e == '0')));
            }
            leng = 0;
            l = i + 1;
        }
    }
    sort(lr.begin(), lr.end());

    dp.assign(n+1, 0);
    ll sum = 0, sumd = 0, i = 0;
    if(lr.size() > 0)
    for(ll j = 1; j <= n; j++)
    {
        if(j == lr[i].first)
        {
            ll si = lr[i].second - lr[i].first + 1;
            ll uc = 0, e = 0, c = 0;
            for(ll k = 0; k < si; k++)
                e += dp[k]*k;
            for(ll k = 0; k < si; k++)
            {
                c += dp[k];
                sum += ((si*(si + 1) + k * (k - 1) )*dp[k])/2;
                dp[k] = 1;
            }
            dp[0] = 0;
            sum += (si*si*si - si)/6 + (si*si + si)/2 + (sumd - e)*si;
            dp[si]+= c + 1;
            sumd = sumd - e + (c)*si + si*(si + 1)/2;
            j = lr[i].second;
            i++;
            if(j == n) break;
        }
        else
            {
                dp[0]++;
                sum += sumd;
            }
    }
    cout << sum << endl;
}


#include <iostream>
#include <vector>
#include <list>
#include <math.h>
#include <bits/stdc++.h>
using namespace std;
#define mp make_pair

typedef long long int ll;
#define pb push_back
vector <pair<ll,ll> > lr;
vector <ll> dp;
int main()
{
    int n; cin >> n;
    int l = 1; int leng = 0;
    for(int i = 1; i <= n; i++)
    {
        char e; cin >> e;
        if(e == '1'){leng ++;}
        if(e=='0' || i == n)
        {
            if(leng > 0)
            {

                leng = 0;
                lr.pb(mp(l , i - (e == '0')));
            }
            leng = 0;
            l = i + 1;
        }
    }
    sort(lr.begin(), lr.end());

    dp.assign(n+1, 0);
    ll sum = 0, sumd = 0, i = 0;
    for(ll j = 1; j <= n; j++)
    {
        if(j == lr[i].first)
        {
            ll si = lr[i].second - lr[i].first + 1;
            ll uc = 0, e = 0, c = 0;
            for(int j = 0; j < si; j++)
                e += dp[j]*j;
            for(int j = 0; j < si; j++)
            {
                c += dp[j];
                sum += ((si*(si + 1) + j * (j - 1) )*dp[j])/2;
                dp[j] = 1;
            }
            dp[0] = 0;
            sum += ((si*si*si - si))/6 + (si*si + si)/2 + (sumd - e)*si;
            dp[si]+= c + 1;
            sumd = sumd - e + (c)*si + si*(si + 1)/2;
            j = lr[i].second;
            i++;
            if(j == n) break;
        }
        else
            {
                dp[0]++;
                sum += sumd;
                //cout << sumd << sum << endl;
            }
    }
    cout << sum << endl;
}


#include <iostream>
#include <vector>
#include <list>
#include <math.h>
#include <bits/stdc++.h>
using namespace std;
#define mp make_pair

typedef long long int ll;
#define pb push_back
vector <pair<int,int> > lr;
vector <ll> dp;
int main()
{
    int n; cin >> n;
    int l = 1; int leng = 0;
    for(int i = 1; i <= n; i++)
    {
        char e; cin >> e;
        if(e == '1'){leng ++;}
        if(e=='0' || i == n)
        {
            if(leng > 0)
            {

                leng = 0;
                lr.pb(mp(l , i - (e == '0')));
            }
            leng = 0;
            l = i + 1;
        }
    }
    sort(lr.begin(), lr.end());

    dp.assign(n+1, 0);
    ll sum = 0, sumd = 0, i = 0;
    for(int j = 1; j <= n; j++)
    {
        if(j == lr[i].first)
        {
            int si = lr[i].second - lr[i].first + 1;
            ll uc = 0, e = 0, c = 0;
            for(int j = 0; j < si; j++)
                e += dp[j]*j;
            for(int j = 0; j < si; j++)
            {
                c += dp[j];
                sum += ((si*(si + 1) + j * (j - 1) )*dp[j])/2;
                dp[j] = 1;
            }
            dp[0] = 0;
            sum += ((si*si*si - si))/6 + (si*si + si)/2 + (sumd - e)*si;
            dp[si]+= c + 1;
            sumd = sumd - e + (c)*si + si*(si + 1)/2;
            j = lr[i].second;
            i++;
            if(j == n) break;
        }
        else
            {
                dp[0]++;
                sum += sumd;
                //cout << sumd << sum << endl;
            }
    }
    cout << sum << endl;
}


#include <iostream>
#include <vector>
#include <list>
#include <math.h>
#include <bits/stdc++.h>
using namespace std;
#define mp make_pair
typedef long long int ll;
#define pb push_back
vector <pair<ll,ll> > lr;
vector <ll> dp;
int main()
{
    int n; cin >> n;
    int l = 1; int leng = 0;
    for(int i = 1; i <= n; i++)
    {
        char e; cin >> e;
        if(e == '1'){leng ++;}
        if(e=='0' || i == n)
        {
            if(leng > 0)
            {

                leng = 0;
                lr.pb(mp(l , i - (e == '0')));
            }
            leng = 0;
            l = i + 1;
        }
    }
    sort(lr.begin(), lr.end());

    dp.assign(n+1, 0);
    ll sum = 0, sumd = 0, i = 0;
    for(ll j = 1; j <= n; j++)
    {
        if(j == lr[i].first)
        {
            ll si = lr[i].second - lr[i].first + 1;
            ll uc = 0, e = 0, c = 0;
            for(ll k = 0; k < si; k++)
                e += dp[k]*k;
            for(ll k = 0; k < si; k++)
            {
                c += dp[k];
                sum += ((si*(si + 1) + k * (k - 1) )*dp[k])/2;
                dp[k] = 1;
            }
            dp[0] = 0;
            sum += (si*si*si - si)/6 + (si*si + si)/2 + (sumd - e)*si;
            dp[si]+= c + 1;
            sumd = sumd - e + (c)*si + si*(si + 1)/2;
            j = lr[i].second;
            i++;
            if(j == n) break;
        }
        else
            {
                dp[0]++;
                sum += sumd;
            }
    }
    cout << sum << endl;
}


#include <iostream>
#include <vector>
#include <list>
#include <math.h>
#include <bits/stdc++.h>
using namespace std;
#define mp make_pair

typedef long long int ll;
#define pb push_back
vector <pair<int,int> > lr;
vector <int> dp;
int main()
{
    int n; cin >> n;
    int l = 1; int leng = 0;
    for(int i = 1; i <= n; i++)
    {
        char e; cin >> e;
        if(e == '1'){leng ++;}
        if(e=='0' || i == n)
        {
            if(leng > 0)
            {

                leng = 0;
                lr.pb(mp(l , i - (e == '0')));
            }
            leng = 0;
            l = i + 1;
        }
    }
    sort(lr.begin(), lr.end());

    dp.assign(n+1, 0);
    ll sum = 0, sumd = 0, i = 0;
    for(int j = 1; j <= n; j++)
    {
        if(j == lr[i].first)
        {
            ll uc = 0;
            int si = lr[i].second - lr[i].first + 1;
            ll e = 0;
            for(int j = 0; j < si; j++)
                e += dp[j]*j;
            ll c = 0;
            for(int j = 0; j < si; j++)
            {
                c += dp[j];
                uc += (dp[j] - 1) * j;
                sum += ( si*(si + 1) + j * (j - 1) )*dp[j]/2;
                dp[j] = 1;
            }
            dp[0] = 0;
            sum += (3*(si*si - si))/2 + 1 + (sumd - e)*si;
            dp[si]+= c + 1;
            sumd += (c+1)*si - uc;
            j = lr[i].second;
            i++;
            if(j == n) break;
        }
        else
            {
                dp[0]++;
                sum += sumd;
            }
    }
    cout << endl << sum << endl;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define For(i,x,y)	for(ll i=(x);i<=(y);++i)
#define FOr(i,x,y)	for(ll i=(x);i>=(y);--i)
#define rep(i,x,y)	for(ll i=(x);i<(y);++i)
#define clr(a,v)	memset(a,v,sizeof(a))
#define cpy(a,b)	memcpy(a,b,sizeof(a))
#define fi	first
#define se	second
#define	pb	push_back
#define mk	make_pair
#define pa	pair<ll,ll>
#define y1	y11111111111111
#define debug	puts("@@@@@@@@@@@@@@@@@@@@@@@")
ll read(){
	ll x=0,f=1;	char ch=getchar();
	for(;ch<'0'||ch>'9';ch=getchar())	if (ch=='-')	f=-1;
	for(;ch>='0'&&ch<='9';ch=getchar())	x=x*10+ch-'0';
	return x*f;
}
void write(ll x){
	if (x<0)	putchar('-'),write(-x);
	else{
		if (x>=10)	write(x/10);
		putchar(x%10+'0');
	}
}
const ll N=500010;
char s[N];
ll v[N],a[N],sum[N],n,m,ans,val;
int main(){
	m=read();
	scanf("%s",s+1);
	For(i,1,m)	if (s[i]!=s[i-1])	v[++n]=s[i]-'0',a[n]=1;
				else				++a[n];
	For(i,1,n)	if (v[i]==0)	ans+=a[i]*val,sum[0]+=a[i];
	else{
		For(j,1,a[i]){
			val+=sum[j-1];
			sum[j]+=sum[j-1];
			sum[j-1]=0;
			ans+=val;
		}
		For(j,1,a[i]){
			++sum[j];
			val+=j;
			ans+=j*(a[i]-j+1);
		}
	}
	cout<<ans<<endl;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define For(i,x,y)	for(ll i=(x);i<=(y);++i)
#define FOr(i,x,y)	for(ll i=(x);i>=(y);--i)
#define rep(i,x,y)	for(ll i=(x);i<(y);++i)
#define clr(a,v)	memset(a,v,sizeof(a))
#define cpy(a,b)	memcpy(a,b,sizeof(a))
#define fi	first
#define se	second
#define	pb	push_back
#define mk	make_pair
#define pa	pair<ll,ll>
#define y1	y11111111111111
#define debug	puts("@@@@@@@@@@@@@@@@@@@@@@@")
ll read(){
	ll x=0,f=1;	char ch=getchar();
	for(;ch<'0'||ch>'9';ch=getchar())	if (ch=='-')	f=-1;
	for(;ch>='0'&&ch<='9';ch=getchar())	x=x*10+ch-'0';
	return x*f;
}
void write(ll x){
	if (x<0)	putchar('-'),write(-x);
	else{
		if (x>=10)	write(x/10);
		putchar(x%10+'0');
	}
}
const ll N=300010;
int main(){
	scanf("%s",s+1);
	For(i,1,n)if (s[i]!=s[i-1])	a[++n]=1;
			else				++a[n];
	For(i,1,n)	if (a[i]>a[q[top]])	L[i]=q[top],q[++top]=i;
				else
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define For(i,x,y)	for(ll i=(x);i<=(y);++i)
#define FOr(i,x,y)	for(ll i=(x);i>=(y);--i)
#define rep(i,x,y)	for(ll i=(x);i<(y);++i)
#define clr(a,v)	memset(a,v,sizeof(a))
#define cpy(a,b)	memcpy(a,b,sizeof(a))
#define fi	first
#define se	second
#define	pb	push_back
#define mk	make_pair
#define pa	pair<ll,ll>
#define y1	y11111111111111
#define debug	puts("@@@@@@@@@@@@@@@@@@@@@@@")
ll read(){
	ll x=0,f=1;	char ch=getchar();
	for(;ch<'0'||ch>'9';ch=getchar())	if (ch=='-')	f=-1;
	for(;ch>='0'&&ch<='9';ch=getchar())	x=x*10+ch-'0';
	return x*f;
}
void write(ll x){
	if (x<0)	putchar('-'),write(-x);
	else{
		if (x>=10)	write(x/10);
		putchar(x%10+'0');
	}
}
const ll N=500010;
char s[N];
vector<ll>LL[N],RR[N];
ll val1[N],val2[N],pos1[N],pos2[N],a[N],q[N],L[N],R[N],siz[N];
ll top,n,m,ans,fang1,fang2,ind1,ind2;
void dfs(ll x){
	if (L[x])dfs(L[x]);
	if (R[x])dfs(R[x]);
	ans+=(siz[L[x]]+1)*(siz[R[x]]+1)*a[x];
	siz[x]=siz[L[x]]+siz[R[x]]+a[x];

	For(i,1,a[x]-1)
		ans+=i*(a[x]-i+1);
//计算答案
	cout<<x<<' '<<ans<<endl;
	ll fang1=0,fang2=0,fang3=0,fang4=0;
	For(i,1,a[x]-1){
		if (LL[pos1[L[x]]].size()>=i+1)
			fang1+=LL[pos1[L[x]]][i],
			fang3+=LL[pos1[L[x]]][i]*i;
		if (RR[pos2[R[x]]].size()>=i+1)
			fang2+=RR[pos2[R[x]]][i],
			fang4+=RR[pos2[R[x]]][i]*i;
		ans+=	val1[pos1[x]]-fang3+
				val2[pos2[x]]-fang4+
				fang1*i+
				fang2*i;
	}
	cout<<x<<' '<<ans<<endl;
	debug;
	if (!L[x]&&!R[x]){
		pos1[x]=++ind1;
		LL[ind1].push_back(0);
		For(i,1,a[x])	LL[ind1].push_back(1),
						val1[ind1]+=i;
		pos2[x]=++ind2;
		RR[ind2].push_back(0);
		For(i,1,a[x])	RR[ind2].push_back(1),
						val2[ind2]+=i;
	}
	else{
		if(!R[x])	pos1[x]=++ind1,LL[ind1].push_back(0);
		else		pos1[x]=pos1[R[x]];
		ll mx=LL[pos1[x]].size()-1;
		For(i,1,a[x]){
			if (LL[pos1[x]].size()<i+1)
				LL[pos1[x]].push_back(1),
				val1[pos1[x]]+=i;
			else	++LL[pos1[x]][mx],
					val1[pos1[x]]+=mx;
		}
		LL[pos1[x]][a[x]]+=siz[L[x]];
		val1[pos1[x]]+=siz[L[x]]*a[x];

		if(!L[x])	pos2[x]=++ind2,RR[ind2].push_back(0);
		else		pos2[x]=pos2[L[x]];
		mx=RR[pos2[x]].size()-1;
		For(i,1,a[x]){
			if (RR[pos2[x]].size()<i+1)
				RR[pos2[x]].push_back(1),
				val2[pos2[x]]+=i;
			else	++RR[pos2[x]][mx],
					val2[pos2[x]]+=mx;
		}
		RR[pos2[x]][a[x]]+=siz[R[x]];
		val2[pos2[x]]+=siz[R[x]]*a[x];
	}
/*	{
		cout<<x<<endl;
		For(i,1,(ll)(LL[pos1[x]].size()-1))cout<<LL[pos1[x]][i]<<' ';cout<<endl;
		For(i,1,(ll)(RR[pos2[x]].size()-1))cout<<RR[pos2[x]][i]<<' ';cout<<endl;
		debug;
	}*/
}
int main(){
	m=read();
	scanf("%s",s+1);
	For(i,1,m)	if (s[i]!=s[i-1])	a[++n]=1;
				else				++a[n];
	For(i,1,n){
		while(top&&a[q[top]]<a[i])	L[i]=q[top--];
		if (top)					R[q[top]]=i;
		q[++top]=i;
	}
	while(top>1)R[q[top-1]]=q[top],--top;
	For(i,1,n)cout<<a[i]<<' '<<L[i]<<' '<<R[i]<<endl;
	dfs(q[1]);
	cout<<ans<<endl;
}


#include "bits/stdc++.h"
using namespace std;
#include "string"
#define int long long
#define pi pair <int, int>
#define ff first
#define ss second
#define boost ios::sync_with_stdio(false);cin.tie(nullptr)
#define endl '\n'

int32_t main() {
	boost;
	int n;
	cin >> n;
	string s;
	cin >> s;
	vector < int > a(n, 0);
	int ans = 0, cur = 0, cnt = 0;
	for(int i = 0; i < n; i++) {
		if(s[i] == '0') {
			ans += cnt;
			cur = 0;
		}
		else {
			cur += 1;
			int l = 0, r = i, pos = i;
			while(l <= r) {
				int m = (l + r) / 2;
				if(a[m] < cur) {
					r = m - 1;
					pos = m;
				}
				else
					l = m + 1;
			}
			cnt += (i - pos + 1);
			ans += cnt;
			for(int j = pos; j <= i; j++)
				a[j]++;
		}
	}
	cout << ans << endl;
}


#pragma GCC optimize("Ofast")
#pragma GCC optimization("unroll-loops, no-stack-protector")
#pragma GCC target("avx,avx2,fma")

#include "bits/stdc++.h"
using namespace std;
#include "string"
#define int long long
#define pi pair <int, int>
#define ff first
#define ss second
#define boost ios::sync_with_stdio(false);cin.tie(nullptr)
#define endl '\n'

typedef struct seg_node {
	int sum = 0;
	int lazy = 0;
}sn;

sn merge(sn a, sn b) {
	sn tmp;
	tmp.sum = a.sum + b.sum;
	return tmp;
}

int n;
class lazy_segment_tree{
private:
	vector< sn > tree;
	vector< int > a;
public:

	lazy_segment_tree(int n) {
		tree.resize(4 * n);
		a.resize(n, 0);
	}

	lazy_segment_tree(vector< int > &v){
		a = v;
		n = v.size();
		tree.resize(4 * v.size());
	}

	void lazy_update(int x, int ss, int ee) {
		if(tree[x].lazy == 0)
			return;
		tree[x].sum += tree[x].lazy;
		if(ss != ee) {
			tree[2 * x].lazy += tree[x].lazy;
			tree[2 * x + 1].lazy += tree[x].lazy;
		}
		tree[x].lazy = 0;
	}

	void built(int x = 1,int ss = 0,int ee = n - 1) {
		if(ss == ee) {
			tree[x].sum =  a[ss];
			return;
		}
		int m = (ss + ee) / 2;
		built(2 * x, ss, m);
		built(2 * x + 1, m + 1, ee);
		tree[x] = merge(tree[2 * x],tree[2 * x + 1]);
	}

	void update(int l, int r, int val, int x = 1, int ss = 0, int ee = n - 1) {
		lazy_update(x, ss, ee);
		if(ss > r || ee < l || l > r)
			return;
		if(ss >= l && ee <= r) {
			tree[x].lazy += val;
			lazy_update(x, ss, ee);
			return;
		}
		int m = (ss + ee) / 2;
		update(l, r, val, 2 * x, ss, m);
		update(l, r, val, 2 * x + 1, m + 1, ee);
		tree[x] = merge(tree[2 * x],tree[2 * x + 1]);
	}

	sn query(int l, int r, int x = 1, int ss = 0, int ee = n - 1) {
		lazy_update(x, ss, ee);
		if(ss > r || ee < l || l > r)
			return tree[0];
		if(ss >= l && ee <= r)
			return tree[x];
		int m = (ss + ee) / 2;
		sn p= query(l, r, 2 * x, ss, m);
		sn q = query(l, r, 2 * x + 1, m + 1, ee);
		sn ans = merge(p, q);
		return ans;
	}
};

int32_t main() {
	boost;
	cin >> n;
	string s;
	cin >> s;
	lazy_segment_tree lst(n);
	int ans = 0, cur = 0, cnt = 0;
	for(int i = 0; i < n; i++) {
		if(s[i] == '0') {
			ans += cnt;
			cur = 0;
		}
		else {
			cur += 1;
			int l = 0, r = i, pos = i;
			while(l <= r) {
				int m = (l + r) / 2;
				if(lst.query(m, m).sum < cur) {
					r = m - 1;
					pos = m;
				}
				else
					l = m + 1;
			}
			cnt += (i - pos + 1);
			ans += cnt;
			lst.update(pos, i, +1);
		}
	}
	cout << ans << endl;
}


#include "bits/stdc++.h"
using namespace std;
#include "string"
#define int long long
#define pi pair <int, int>
#define ff first
#define ss second
#define boost ios::sync_with_stdio(false);cin.tie(nullptr)
#define endl '\n'

int32_t main() {
	boost;
	int n;
	cin >> n;
	string s;
	cin >> s;
	stack < pi > st;
	st.push({n + 1, -1});
	int ans = 0, cnt = 0;
	for(int i = 0; i < n; i++) {
		if(s[i] == '0') {
			ans += cnt;
			continue;
		}
		int j = i, cur = 0;
		while(j < n && s[j] == s[i]) {
			cur++;
			while(st.top().ff < cur)
				st.pop();
			cnt += j - st.top().ss;
			ans += cnt;
			j++;
		}
		j = i;
		while(j < n && s[j] == s[i])
			st.push({cur--, j++});
		i = j - 1;
	}
	cout << ans << endl;
}


#include "bits/stdc++.h"
using namespace std;
#include "string"
#define int long long
#define pi pair <int, int>
#define ff first
#define ss second
#define boost ios::sync_with_stdio(false);cin.tie(nullptr)
#define endl '\n'

typedef struct seg_node {
	int sum = 0;
	int lazy = 0;
}sn;

sn merge(sn a, sn b) {
	sn tmp;
	tmp.sum = a.sum + b.sum;
	return tmp;
}

int n;
class lazy_segment_tree{
private:
	vector< sn > tree;
	vector< int > a;
public:

	lazy_segment_tree(int n) {
		tree.resize(4 * n);
		a.resize(n, 0);
	}

	lazy_segment_tree(vector< int > &v){
		a = v;
		n = v.size();
		tree.resize(4 * v.size());
	}

	void lazy_update(int x, int ss, int ee) {
		if(tree[x].lazy == 0)
			return;
		tree[x].sum += tree[x].lazy;
		if(ss != ee) {
			tree[2 * x].lazy += tree[x].lazy;
			tree[2 * x + 1].lazy += tree[x].lazy;
		}
		tree[x].lazy = 0;
	}

	void built(int x = 1,int ss = 0,int ee = n - 1) {
		if(ss == ee) {
			tree[x].sum =  a[ss];
			return;
		}
		int m = (ss + ee) / 2;
		built(2 * x, ss, m);
		built(2 * x + 1, m + 1, ee);
		tree[x] = merge(tree[2 * x],tree[2 * x + 1]);
	}

	void update(int l, int r, int val, int x = 1, int ss = 0, int ee = n - 1) {
		lazy_update(x, ss, ee);
		if(ss > r || ee < l || l > r)
			return;
		if(ss >= l && ee <= r) {
			tree[x].lazy += val;
			lazy_update(x, ss, ee);
			return;
		}
		int m = (ss + ee) / 2;
		update(l, r, val, 2 * x, ss, m);
		update(l, r, val, 2 * x + 1, m + 1, ee);
		tree[x] = merge(tree[2 * x],tree[2 * x + 1]);
	}

	sn query(int l, int r, int x = 1, int ss = 0, int ee = n - 1) {
		lazy_update(x, ss, ee);
		if(ss > r || ee < l || l > r)
			return tree[0];
		if(ss >= l && ee <= r)
			return tree[x];
		int m = (ss + ee) / 2;
		sn p= query(l, r, 2 * x, ss, m);
		sn q = query(l, r, 2 * x + 1, m + 1, ee);
		sn ans = merge(p, q);
		return ans;
	}
};

int32_t main() {
	boost;
	cin >> n;
	string s;
	cin >> s;
	stack < pi > st;
	st.push({n + 1, -1});
	int ans = 0, cnt = 0;
	for(int i = 0; i < n; i++) {
		if(s[i] == '0') {
			ans += cnt;
			continue;
		}
		int j = i, cur = 0;
		while(j < n && s[j] == s[i]) {
			cur++;
			while(st.top().ff < cur)
				st.pop();
			cnt += j - st.top().ss;
			ans += cnt;
			j++;
		}
		j = i;
		while(j < n && s[j] == s[i])
			st.push({cur--, j++});
		i = j - 1;
	}
	cout << ans << endl;
}


#include "bits/stdc++.h"
using namespace std;
#include "string"
#define int long long
#define pi pair <int, int>
#define ff first
#define ss second
#define boost ios::sync_with_stdio(false);cin.tie(nullptr)
#define endl '\n'

typedef struct seg_node {
	int sum = 0;
	int lazy = 0;
}sn;

sn merge(sn a, sn b) {
	sn tmp;
	tmp.sum = a.sum + b.sum;
	return tmp;
}

int n;
class lazy_segment_tree{
private:
	vector< sn > tree;
	vector< int >a;
public:
	lazy_segment_tree(int n) {
		tree.resize(4 * n);
		a.resize(n, 0);
	}

	lazy_segment_tree(vector< int > &v){
		a = v;
		n = v.size();
		tree.resize(4 * v.size());
	}

	void lazy_update(int x, int ss, int ee) {
		if(tree[x].lazy == 0)
			return;
		tree[x].sum += tree[x].lazy;
		if(ss != ee) {
			tree[2 * x].lazy += tree[x].lazy;
			tree[2 * x + 1].lazy += tree[x].lazy;
		}
		tree[x].lazy = 0;
	}

	void built(int x = 1,int ss = 0,int ee = n - 1) {
		if(ss == ee) {
			tree[x].sum =  a[ss];
			return;
		}
		int m = (ss + ee) / 2;
		built(2 * x, ss, m);
		built(2 * x + 1, m + 1, ee);
		tree[x] = merge(tree[2 * x],tree[2 * x + 1]);
	}

	void update(int l, int r, int val, int x = 1, int ss = 0, int ee = n - 1) {
		lazy_update(x, ss, ee);
		if(ss > r || ee < l || l > r)
			return;
		if(ss >= l && ee <= r) {
			tree[x].lazy += val;
			lazy_update(x, ss, ee);
			return;
		}
		int m = (ss + ee) / 2;
		update(l, r, val, 2 * x, ss, m);
		update(l, r, val, 2 * x + 1, m + 1, ee);
		tree[x] = merge(tree[2 * x],tree[2 * x + 1]);
	}

	sn query(int l, int r, int x = 1, int ss = 0, int ee = n - 1) {
		lazy_update(x, ss, ee);
		if(ss > r || ee < l || l > r)
			return tree[0];
		if(ss >= l && ee <= r)
			return tree[x];
		int m = (ss + ee) / 2;
		sn p= query(l, r, 2 * x, ss, m);
		sn q = query(l, r, 2 * x + 1, m + 1, ee);
		sn ans = merge(p, q);
		return ans;
	}
};

int32_t main() {
	boost;
	cin >> n;
	string s;
	cin >> s;
	lazy_segment_tree lst(n);
	int ans = 0, cur = 0, cnt = 0;
	for(int i = 0; i < n; i++) {
		if(s[i] == '0') {
			ans += cnt;
			cur = 0;
		}
		else {
			cur += 1;
			int l = 0, r = i, pos = i;
			while(l <= r) {
				int m = (l + r) / 2;
				if(lst.query(m, m).sum < cur) {
					r = m - 1;
					pos = m;
				}
				else
					l = m + 1;
			}
			cnt += (i - pos + 1);
			ans += cnt;
			lst.update(pos, i, +1);
		}
	}
	cout << ans << endl;
}


#include "bits/stdc++.h"
using namespace std;
#include "string"
#define int long long
#define pi pair <int, int>
#define ff first
#define ss second
#define boost ios::sync_with_stdio(false);cin.tie(nullptr)
#define endl '\n'

const int M = 1e9 + 7;

// AB segment
int ABnotOverlap(int n, int a, int b) {
	// A left and B right
	// ... A ... B ...
	if(n - a - b < 0)
		return 0;
	int ans = (n - a - b + 2) * (n - a - b + 1) / 2;

	// based on symmetry simmilar for .... B ... A ...
	return 2 * ans;
}

// AB segment
int ABOverlap(int n, int a, int b) {
	int ans = (n - a + 1) * (n - b + 1);
	ans -= ABnotOverlap(n, a, b);
	return ans;
}

// AABB squre
int AABBOverlap(int n, int a, int b) {
	// x of both overlap and y of both overlap
	// based on symmerty we can prove that x of both = y of both
	// ans = (x of both) * (x of both)

	int ans = ABOverlap(n, a, b);
	ans %= M;
	return ans * ans;
}

// AABB square
int AABBnotOverlap(int n, int a, int b) {
	int ans = (n - a + 1) * (n - b + 1);
	ans %= M;
	ans = (ans * ans) % M;
	ans -= AABBOverlap(n, a, b);
	ans %= M;
	ans = (ans + M) % M;
	return ans;
}

int32_t main() {
	boost;
	int t;
	cin >> t;
	while(t--) {
		int n, a, b;
		cin >> n >> a >> b;
		int ans = AABBnotOverlap(n, a, b);
		cout << ans << endl;
	}
}


// Marcin Knapik
#include<bits/stdc++.h>
#pragma GCC optimize("O3")
// #pragma GCC optimize("Ofast")
// #pragma GCC optimize("unroll-loops")

using namespace std;

// #include <ext/pb_ds/assoc_container.hpp> // order_of_key
// #include <ext/pb_ds/tree_policy.hpp> // find by order
// using namespace __gnu_pbds;
// #define ordered_set tree< int , null_type,less< int >, rb_tree_tag,tree_order_statistics_node_update>

// const ll MAX_LL = 0xFFFFFFFFFFFFFFFF;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define losuj(a, b) uniform_int_distribution<ll>(a, b)(rng)

typedef long double             ld;
typedef long long               ll;
typedef pair<int, int>          ii;
typedef vector<int>             vi;
typedef vector<ll>              vll;
typedef vector<vll>             vvll;
typedef vector<ii>              vii;
typedef vector<vi>              vvi;
typedef vector<vii>             vvii;
#define pll pair<long long, long long>
#define ull unsigned long long

#define sz(a)                   (int)(a).size()
#define pb                      push_back
#define all(c)                  (c).begin(), (c).end()
#define rall(c)                 (c).rbegin(), (c).rend()
#define FOR(i, a)               for (int i = 0; i < (a); i++)
#define f                       first
#define s                       second

template <class T> inline bool setmin(T &a, T b){if (a > b)return a = b, 1;return 0;}
template <class T> inline bool setmax(T &a, T b){if (a < b)return a = b, 1;return 0;}

template<class T> inline T fast(T a,T b,T mod) {ll res = 1; while(b){if(b&1) res = (res*a)%mod;a = (a*a)%mod;b >>= 1;}return res;}
template<class T> istream &operator>>(istream &os, vector<T> &container){for (auto &u : container)os >> u;return os;}
template<class T> ostream &operator<<(ostream &os, const vector<T> &container){for (auto &u : container)os << u << " ";return os;}
template<class T> inline T gcd(T a, T b) { while (b)swap(a %= b, b); return abs(a); }

const ll INF = 1e9 + 7;
const ll mod = 998244353;
const ll BIG_INF = 1e18 + 7;
const ll N = 1e6+7;
const ll T = 1<<20;
const ld inf = 1e18;

int n, k;

ll lazy[T * 2];
ll tree[T * 2];

void push(int v, int len){
    // cout << T * 2 - 1 << ' ' << v << endl;
    tree[v] += 1ll * lazy[v] * len;

    if(v < T){
        lazy[v + v] += lazy[v];
        lazy[v + v + 1] += lazy[v];
    }

    lazy[v] = 0;
}

ll suma(int pocz, int kon, int u = 1, int lo = 0, int hi = T - 1){
    // cout << pocz << ' ' << kon << ' ' << lo << ' ' << hi << endl;
    push(u, hi - lo + 1);

    if(pocz > hi or lo > kon)
        return 0;
    if(pocz <= lo and kon >= hi)
        return tree[u];

    int mid = (lo + hi) / 2;

    return suma(pocz, kon, u + u, lo, mid) + suma(pocz, kon, u + u + 1, mid + 1, hi);
}

void add(int pocz, int kon, int u = 1, int lo = 0, int hi = T - 1){
    push(u, hi - lo + 1);

    if(pocz > hi or lo > kon)
        return;
    if(pocz <= lo and kon >= hi){
        lazy[u] ++;
        push(u, hi - lo + 1);
        return;
    }

    int mid = (lo + hi) / 2;
    add(pocz, kon, u + u, lo, mid);
    add(pocz, kon, u + u + 1, mid + 1, hi);
    tree[u] = tree[u + u] + tree[u + u + 1];
}

void solve(){
    cin >> n;

    string s;
    cin >> s;

    int start = -1;
    ll ans = 0;

    set<int> skoki;

    for(int i = 0; i < n; i++){
        // cout << "i: " << i << endl;
        if(s[i] == '1'){
            if(start == -1)
                start = i;
            skoki.insert(i);
            add(start, i);

            auto it = skoki.find(start);
            if(it != skoki.begin()){
                // cout << "usuwam"
                it = prev(it);
                add(*it + 1, start - 1);
                skoki.erase(it);
            }
            else if(suma(0, 0) < suma(start, start)){
                add(0, start - 1);
            }

            // cout << "SKOKI: ";
            // for(auto & u : skoki)
                // cout << u << ' ';
            // cout << endl;
        }
        else
            start = -1;
        cout << "SUMAA " << suma(0, T - 1)<< endl;
        ans += suma(0, T - 1);
    }
    cout << ans << '\n';
}

signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);

    int t = 1;
    // cin >> t;

    while(t--){
        solve();
    }
}


// Marcin Knapik
#include<bits/stdc++.h>
#pragma GCC optimize("O3")
// #pragma GCC optimize("Ofast")
// #pragma GCC optimize("unroll-loops")

using namespace std;

// #include <ext/pb_ds/assoc_container.hpp> // order_of_key
// #include <ext/pb_ds/tree_policy.hpp> // find by order
// using namespace __gnu_pbds;
// #define ordered_set tree< int , null_type,less< int >, rb_tree_tag,tree_order_statistics_node_update>

// const ll MAX_LL = 0xFFFFFFFFFFFFFFFF;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define losuj(a, b) uniform_int_distribution<ll>(a, b)(rng)

typedef long double             ld;
typedef long long               ll;
typedef pair<int, int>          ii;
typedef vector<int>             vi;
typedef vector<ll>              vll;
typedef vector<vll>             vvll;
typedef vector<ii>              vii;
typedef vector<vi>              vvi;
typedef vector<vii>             vvii;
#define pll pair<long long, long long>
#define ull unsigned long long

#define sz(a)                   (int)(a).size()
#define pb                      push_back
#define all(c)                  (c).begin(), (c).end()
#define rall(c)                 (c).rbegin(), (c).rend()
#define FOR(i, a)               for (int i = 0; i < (a); i++)
#define f                       first
#define s                       second

template <class T> inline bool setmin(T &a, T b){if (a > b)return a = b, 1;return 0;}
template <class T> inline bool setmax(T &a, T b){if (a < b)return a = b, 1;return 0;}

template<class T> inline T fast(T a,T b,T mod) {ll res = 1; while(b){if(b&1) res = (res*a)%mod;a = (a*a)%mod;b >>= 1;}return res;}
template<class T> istream &operator>>(istream &os, vector<T> &container){for (auto &u : container)os >> u;return os;}
template<class T> ostream &operator<<(ostream &os, const vector<T> &container){for (auto &u : container)os << u << " ";return os;}
template<class T> inline T gcd(T a, T b) { while (b)swap(a %= b, b); return abs(a); }

const ll INF = 1e9 + 7;
const ll mod = 998244353;
const ll BIG_INF = 1e18 + 7;
const ll N = 1e6+7;
const ll T = 1<<20;
const ld inf = 1e18;

int n, k;

ll lazy[T * 2];
ll tree[T * 2];

void push(int v, int len){
    // cout << T * 2 - 1 << ' ' << v << endl;
    tree[v] += 1ll * lazy[v] * len;

    if(v < T){
        lazy[v + v] += lazy[v];
        lazy[v + v + 1] += lazy[v];
    }

    lazy[v] = 0;
}

ll suma(int pocz, int kon, int u = 1, int lo = 0, int hi = T - 1){
    // cout << pocz << ' ' << kon << ' ' << lo << ' ' << hi << endl;
    push(u, hi - lo + 1);

    if(pocz > hi or lo > kon)
        return 0;
    if(pocz <= lo and kon >= hi)
        return tree[u];

    int mid = (lo + hi) / 2;

    return suma(pocz, kon, u + u, lo, mid) + suma(pocz, kon, u + u + 1, mid + 1, hi);
}

void add(int pocz, int kon, int u = 1, int lo = 0, int hi = T - 1){
    push(u, hi - lo + 1);

    if(pocz > hi or lo > kon)
        return;
    if(pocz <= lo and kon >= hi){
        lazy[u] ++;
        push(u, hi - lo + 1);
        return;
    }

    int mid = (lo + hi) / 2;
    add(pocz, kon, u + u, lo, mid);
    add(pocz, kon, u + u + 1, mid + 1, hi);
    tree[u] = tree[u + u] + tree[u + u + 1];
}

void solve(){
    cin >> n;

    string s;
    cin >> s;

    int start = -1;
    ll ans = 0;

    for(int i = 0; i < n; i++){
        if(s[i] == '1'){
            if(start == -1)
                start = i;
            add(start, i);
            int val = suma(start, start);
            if(start > 0 and suma(start - 1, start - 1) < val){
                int L = -1;
                int R = start - 1;

                while(R - L > 1){
                    int mid = (R + L) / 2;
                    (suma(mid, mid) < val ? R : L) = mid;
                }
                add(R, start - 1);
            }
        }
        else{
            start = -1;
        }
        ans += suma(0, T - 1);
    }
    cout << ans << '\n';
}

signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);

    int t = 1;
    // cin >> t;

    while(t--){
        solve();
    }
}


// Marcin Knapik
#include<bits/stdc++.h>
#pragma GCC optimize("O3")
// #pragma GCC optimize("Ofast")
// #pragma GCC optimize("unroll-loops")

using namespace std;

// #include <ext/pb_ds/assoc_container.hpp> // order_of_key
// #include <ext/pb_ds/tree_policy.hpp> // find by order
// using namespace __gnu_pbds;
// #define ordered_set tree< int , null_type,less< int >, rb_tree_tag,tree_order_statistics_node_update>

// const ll MAX_LL = 0xFFFFFFFFFFFFFFFF;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define losuj(a, b) uniform_int_distribution<ll>(a, b)(rng)

typedef long double             ld;
typedef long long               ll;
typedef pair<int, int>          ii;
typedef vector<int>             vi;
typedef vector<ll>              vll;
typedef vector<vll>             vvll;
typedef vector<ii>              vii;
typedef vector<vi>              vvi;
typedef vector<vii>             vvii;
#define pll pair<long long, long long>
#define ull unsigned long long

#define sz(a)                   (int)(a).size()
#define pb                      push_back
#define all(c)                  (c).begin(), (c).end()
#define rall(c)                 (c).rbegin(), (c).rend()
#define FOR(i, a)               for (int i = 0; i < (a); i++)
#define f                       first
#define s                       second

template <class T> inline bool setmin(T &a, T b){if (a > b)return a = b, 1;return 0;}
template <class T> inline bool setmax(T &a, T b){if (a < b)return a = b, 1;return 0;}

template<class T> inline T fast(T a,T b,T mod) {ll res = 1; while(b){if(b&1) res = (res*a)%mod;a = (a*a)%mod;b >>= 1;}return res;}
template<class T> istream &operator>>(istream &os, vector<T> &container){for (auto &u : container)os >> u;return os;}
template<class T> ostream &operator<<(ostream &os, const vector<T> &container){for (auto &u : container)os << u << " ";return os;}
template<class T> inline T gcd(T a, T b) { while (b)swap(a %= b, b); return abs(a); }

const ll INF = 1e9 + 7;
const ll mod = 998244353;
const ll BIG_INF = 1e18 + 7;
const ll N = 1e6+7;
const ll T = 1<<20;
const ld inf = 1e18;

int n, k;

ll wynik(int wys, int ile_c){
    if(ile_c >= wys)
        return wys;

    int kaw = wys / (ile_c + 1);
    int suma = kaw * (ile_c + 1);

    int dluzsze = wys - suma;

    return (ile_c + 1 - dluzsze) * 1ll * kaw * kaw + dluzsze * 1ll * (kaw + 1) * (kaw + 1);
}

ll poprawa(int poz, vi & ile, vi & tab){
    return wynik(tab[poz], ile[poz]) - wynik(tab[poz], ile[poz] + 1);
}

void solve(){
    cin >> n >> k;

    vi tab(n);
    cin >> tab;
    sort(all(tab));
    vi ile(n);

    set<pair<ll,int> > secik;
    ll suma = 0;

    for(int i = 0; i < n; i++){
        suma += wynik(tab[i], 0);
        secik.insert({poprawa(i, ile, tab), i});
    }

    // cout << suma << endl;

    for(int i = 0; i < k - n; i++){
        assert(sz(secik));
        // cout << i << endl;
        pair<ll, int> it = *prev(secik.end());
        secik.erase(it);

        suma -= it.f;
        ile[it.s]++;
        // cout << "XD " << endl;
        secik.insert({poprawa(it.s, ile, tab), it.s});
    }
    // cout << "LEL " << endl;
    cout << suma << '\n';
}

signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);

    int t = 1;
    // cin >> t;

    while(t--){
        solve();
    }
}


// Marcin Knapik
#include<bits/stdc++.h>
#pragma GCC optimize("O3")
// #pragma GCC optimize("Ofast")
// #pragma GCC optimize("unroll-loops")

using namespace std;

// #include <ext/pb_ds/assoc_container.hpp> // order_of_key
// #include <ext/pb_ds/tree_policy.hpp> // find by order
// using namespace __gnu_pbds;
// #define ordered_set tree< int , null_type,less< int >, rb_tree_tag,tree_order_statistics_node_update>

// const ll MAX_LL = 0xFFFFFFFFFFFFFFFF;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define losuj(a, b) uniform_int_distribution<ll>(a, b)(rng)

typedef long double             ld;
typedef long long               ll;
typedef pair<int, int>          ii;
typedef vector<int>             vi;
typedef vector<ll>              vll;
typedef vector<vll>             vvll;
typedef vector<ii>              vii;
typedef vector<vi>              vvi;
typedef vector<vii>             vvii;
#define pll pair<long long, long long>
#define ull unsigned long long

#define sz(a)                   (int)(a).size()
#define pb                      push_back
#define all(c)                  (c).begin(), (c).end()
#define rall(c)                 (c).rbegin(), (c).rend()
#define FOR(i, a)               for (int i = 0; i < (a); i++)
#define f                       first
#define s                       second

template <class T> inline bool setmin(T &a, T b){if (a > b)return a = b, 1;return 0;}
template <class T> inline bool setmax(T &a, T b){if (a < b)return a = b, 1;return 0;}

template<class T> inline T fast(T a,T b,T mod) {ll res = 1; while(b){if(b&1) res = (res*a)%mod;a = (a*a)%mod;b >>= 1;}return res;}
template<class T> istream &operator>>(istream &os, vector<T> &container){for (auto &u : container)os >> u;return os;}
template<class T> ostream &operator<<(ostream &os, const vector<T> &container){for (auto &u : container)os << u << " ";return os;}
template<class T> inline T gcd(T a, T b) { while (b)swap(a %= b, b); return abs(a); }

const ll INF = 1e9 + 7;
const ll mod = 998244353;
const ll BIG_INF = 1e18 + 7;
const ll N = 1e6+7;
const ll T = 1<<20;
const ld inf = 1e18;

int n, k;

ll lazy[T * 2];
ll tree[T * 2];

void push(int v, int len){
    // cout << T * 2 - 1 << ' ' << v << endl;
    tree[v] += 1ll * lazy[v] * len;

    if(v < T){
        lazy[v + v] += lazy[v];
        lazy[v + v + 1] += lazy[v];
    }

    lazy[v] = 0;
}

ll suma(int pocz, int kon, int u = 1, int lo = 0, int hi = T - 1){
    // cout << pocz << ' ' << kon << ' ' << lo << ' ' << hi << endl;
    push(u, hi - lo + 1);

    if(pocz > hi or lo > kon)
        return 0;
    if(pocz <= lo and kon >= hi)
        return tree[u];

    int mid = (lo + hi) / 2;

    return suma(pocz, kon, u + u, lo, mid) + suma(pocz, kon, u + u + 1, mid + 1, hi);
}

void add(int pocz, int kon, int u = 1, int lo = 0, int hi = T - 1){
    push(u, hi - lo + 1);

    if(pocz > hi or lo > kon)
        return;
    if(pocz <= lo and kon >= hi){
        lazy[u] ++;
        push(u, hi - lo + 1);
        return;
    }

    int mid = (lo + hi) / 2;
    add(pocz, kon, u + u, lo, mid);
    add(pocz, kon, u + u + 1, mid + 1, hi);
    tree[u] = tree[u + u] + tree[u + u + 1];
}

void solve(){
    cin >> n;

    string s;
    cin >> s;

    int start = -1;
    ll ans = 0;

    set<int> skoki;

    for(int i = 0; i < n; i++){
        // cout << "i: " << i << endl;
        if(s[i] == '1'){
            if(start == -1)
                start = i;
            skoki.insert(i);
            add(start, i);

            auto it = skoki.find(start);
            if(it != skoki.begin()){
                // cout << "usuwam"
                it = prev(it);
                add(*it + 1, start - 1);
                skoki.erase(it);
            }
            else if(suma(0, 0) < suma(start, start)){
                add(0, start - 1);
            }

            // cout << "SKOKI: ";
            // for(auto & u : skoki)
                // cout << u << ' ';
            // cout << endl;
        }
        else
            start = -1;
        // cout << "SUMAA " << suma(0, T - 1)<< endl;
        ans += suma(0, T - 1);
    }
    cout << ans << '\n';
}

signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);

    int t = 1;
    // cin >> t;

    while(t--){
        solve();
    }
}


#include <bits/stdc++.h>
#include <unordered_set>
#include <unordered_map>
#include <random>
using namespace std;
#define ll long long
#define fr first
#define sc second
#define pll pair<ll, ll>
#define all(v) v.begin(), v.end()

ll hist[550000]; // hist[x] : 높이가 x인 히스토그램 좌표
ll ans; //정답 저장
ll cnt; //연속한 1의 개수 저장
ll sum; //히스토그램의 넓이 저장
ll N;
string s;

void solve(int tc) {
	cin >> N >> s;
	for (int i = 0; i < N; i++) {
		if (s[i] == '1') {
			cnt++;
			int j = hist[cnt];
			sum += i - j + 1;
			if (i + 1 < N && s[i + 1] == '0') {
				for (int j = i - cnt + 1; j <= i; j++) hist[i - j + 1] = j + 1;
			}
		}
		else if (s[i] == '0') {
			cnt = 0;
		}
		ans += sum;
	}
	cout << ans << '\n';
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	if (0) {
		int T; cin >> T;
		for (int i = 1; i <= T; i++) solve(i);
	}
	else {
		solve(0);
	}
	return 0;
}


#include <bits/stdc++.h>
#include <unordered_set>
#include <unordered_map>
#include <random>
using namespace std;
#define ll long long
#define fr first
#define sc second
#define pll pair<ll, ll>
#define all(v) v.begin(), v.end()

const int INF = 2e9;
int N;
string s;

void solve(int tc) {
	cin >> N >> s;

	vector<pll> v;
	v.push_back({ INF, -1 });
	ll sum = 0, ans = 0, cnt = 0;

	for (int i = 0; i < s.size(); i++) {
		if (s[i] == '1') {
			cnt++;
			while (v.back().fr <= cnt) {
				pll cur = v.back();
				v.pop_back();
				sum -= cur.fr * (cur.sc - v.back().sc);
			}
			ans += cnt * (i - cnt - v.back().sc);
			ans += cnt * (cnt + 1) / 2;
		}
		else {
			for (int j = i - cnt; j < i; j++) {
				sum += (j - v.back().sc) * (i - j);
				v.push_back({ i - j, j });
			}
			cnt = 0;
		}
		ans += sum;

		//cout << i << ' ' << sum << ' ' << ans<<'\n';
	}
	cout << ans << '\n';
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	if (0) {
		int T; cin >> T;
		for (int i = 1; i <= T; i++) solve(i);
	}
	else {
		solve(0);
	}
	return 0;
}


#include <bits/stdc++.h>
#include <unordered_set>
#include <unordered_map>
#include <random>
using namespace std;
#define ll long long
#define fr first
#define sc second
#define pll pair<ll, ll>
#define all(v) v.begin(), v.end()

ll hist[550000]; // hist[x] : 높이가 x인 히스토그램 좌표
ll ans; //정답 저장
ll cnt; //연속한 1의 개수 저장
ll sum; //히스토그램의 넓이 저장
ll N;
string s;

void solve(int tc) {
	cin >> N >> s;
	for (int i = 0; i < N; i++) {
		if (s[i] == '1') {
			cnt++;
			int j = hist[cnt];
			sum += i - j + 1;
			if (i + 1 < N && s[i + 1] == '0') {
				for (int j = i - cnt + 1; j <= i; j++) hist[i - j + 1] = j + 1;
			}
		}
		else if (s[i] == '0') {
			cnt = 0;
		}
		ans += sum;
		cout << sum << '\n';
	}
	cout << ans << '\n';
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	if (0) {
		int T; cin >> T;
		for (int i = 1; i <= T; i++) solve(i);
	}
	else {
		solve(0);
	}
	return 0;
}


#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include <bits/stdc++.h>
using namespace std;
#define SORT(A) std::sort(A.begin(), A.end())
#define RSORT(A) std::sort(A.begin(), A.end(), std::greater<>())
#define FR(A, e) for (auto& e : A)
#define show(A) for (auto& e : A) {cout << e << " ";}; cout << endl;
#define within(x,_left,_right) (_left <= x && x <= _right)
#define rwithin(x, _l, _r) (_l < x && x < _r)
#define all(A) A.begin(),A.end()
#define rall(A) (A).rbegin(),(A).rend()
#define lb lower_bound
#define ub upper_bound
#define pb push_back
#define sz(x) ((int)x.size())
#define complete_unique(a) a.erase(unique(a.begin(),a.end()),a.end())
#define bitcnt(x) (__builtin_popcountll(x))
#define fi first
#define se second
#define mst(x, bit) memset(x, bit, sizeof(x))
#define chmax(a, b) a = max(a, b)
#define chmin(a, b) a = min(a, b)
using LL = long long;
using db = double;
using VI = vector<int>;
using VVI = vector<VI>;
using VVVI = vector<VVI>;
using VL = vector<LL>;
using VVL = vector<VL>;
using VVVL = vector<VVL>;
using VS = vector<string>;
const int inf = 0x3f3f3f3f;
const int rinf = 0xc0c0c0c0;
const LL MOD = 1e9 + 7;
const LL LMAX = 0x7fffffffffffffff;
const LL LMIN = 0x8000000000000000;
typedef std::pair<int, int> PII;
typedef std::pair<LL, LL> PLL;
typedef std::pair<int, char> PIC;
// int dx[4] = {1, -1, 0, 0}; // 冯诺依曼型邻居
// int dy[4] = {0, 0, 1, -1};
// int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1}; // 摩尔型邻居
// int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};
// 字符串类:模拟规律 -> Greedy -> dp -> kmp || Automation (注意数据量， 先数学后暴力)
// #include<iomanip> cout << fixed <<  setprecision(k) 输出k位精度

// 调试专用
#define debug cout << " ---- ok ---- \n";
template<typename T>
void print(vector<vector<T>> a){
    for (int i = 0; i < a.size(); ++ i){
        for (int j = 0; j < a[i].size(); ++ j) cout << a[i][j] << (j == sz(a[i]) - 1 ? '\n' : ' ');
    }
}
template<typename T>
void print(T *a, int len){
    for (int i = 0; i < len; ++ i) cout << a[i] << " ";
    cout << endl;
}
template<typename T>
void print(T **a, int row, int col){
    for (int i = 0; i < row; ++ i){
        for (int j = 0; j < col; ++ j) cout << a[i][j] << (j == col - 1 ? '\n' : ' ');
    }
}
template<typename T1, typename T2>
void print(const vector<pair<T1, T2>> a){
    for (auto &e: a) cout << "(" << e.first << ", " << e.second << ")\n";
}
template<typename... Args>
void _SHOW_ALL(Args... args){ }
template<typename T, typename... Args>
void _SHOW_ALL(T val, Args... args){
    cout << val << ", ";
    _SHOW_ALL(args...);
}
template<typename T, typename... Args>
void to_brackets(T val, Args... args){
    cout << "(";
    _SHOW_ALL(val, args...);
    cout << ")\n";
}

template<typename... Args>
void wprint(Args... args){ cout << '\n'; }
template<typename T, typename... Args>
void wprint(T val, Args... args){
    cout << val << " ";
    wprint(args...);
}

inline int read(){
    /* 注意假如为 long long 时需要修改 */
    char c = getchar();
    int x = 0, f = 1;
    while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); }
    while (isdigit(c)) x = (x << 3) + (x << 1) + (c^48), c = getchar();
    return f * x;
}
inline LL readl(){
    char c = getchar();
    LL x = 0, f = 1;
    while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); }
    while (isdigit(c)) x = (x << 3) + (x << 1) + (c^48), c = getchar();
    return f * x;
}
void write(int a){
    if (a < 0) putchar('-'), a = -a;
    if (a >= 10) write(a / 10);
    putchar(a % 10 + 48);
}

const int maxn = 5e5 + 50;
map<int, int> block;
int dp[maxn];
void solve(){
    string ss; cin >> ss;
    int n = ss.length();
    for (int i = 0; i <= n; ++ i) dp[i] = 0;
    PII seg = make_pair(0, 0);
    for (int i = 1; i <= n; ++ i){
        if (ss[i - 1] == '0') {
            dp[i] = dp[i - 1];
            if (seg.first != 0) {
                block[seg.first] = seg.second;
            }
            seg = {0, 0};
        }
        else {
            if (seg.first == 0) seg.second = i;
            ++ seg.first;
            auto iter = block.lower_bound(seg.first);
            if (iter == block.end()){
                dp[i] = dp[i - 1] + i;
            }
            else {
                int pos = (*iter).second, len = (*iter).first;
                // cout << "参数为:";
                // wprint(pos, len, seg.first);
                // cout << "pos为:" << pos << '\n';
                // cout << "x为" << (pos + len + 1 - seg.first) << '\n';
                dp[i] = dp[i - 1] + (i - (pos + len + 1 - seg.first) + 1);
            }
        }
        // cout << "第" << i << "个:" << dp[i] << '\n';
    }
    LL sum = 0;
    for (int i = 1; i <= n; ++ i) sum += dp[i];
    cout << sum << '\n';
}

int main(){
    // int t = 1;
    int t = read();
    while (t--) solve();
    return 0;
}


#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include <bits/stdc++.h>
using namespace std;
#define SORT(A) std::sort(A.begin(), A.end())
#define RSORT(A) std::sort(A.begin(), A.end(), std::greater<>())
#define FR(A, e) for (auto& e : A)
#define show(A) for (auto& e : A) {cout << e << " ";}; cout << endl;
#define within(x,_left,_right) (_left <= x && x <= _right)
#define rwithin(x, _l, _r) (_l < x && x < _r)
#define all(A) A.begin(),A.end()
#define rall(A) (A).rbegin(),(A).rend()
#define lb lower_bound
#define ub upper_bound
#define pb push_back
#define sz(x) ((int)x.size())
#define complete_unique(a) a.erase(unique(a.begin(),a.end()),a.end())
#define bitcnt(x) (__builtin_popcountll(x))
#define fi first
#define se second
#define mst(x, bit) memset(x, bit, sizeof(x))
#define chmax(a, b) a = max(a, b)
#define chmin(a, b) a = min(a, b)
using LL = long long;
using db = double;
using VI = vector<int>;
using VVI = vector<VI>;
using VVVI = vector<VVI>;
using VL = vector<LL>;
using VVL = vector<VL>;
using VVVL = vector<VVL>;
using VS = vector<string>;
const int inf = 0x3f3f3f3f;
const int rinf = 0xc0c0c0c0;
const LL MOD = 1e9 + 7;
const LL LMAX = 0x7fffffffffffffff;
const LL LMIN = 0x8000000000000000;
typedef std::pair<int, int> PII;
typedef std::pair<LL, LL> PLL;
typedef std::pair<int, char> PIC;
// int dx[4] = {1, -1, 0, 0}; // 冯诺依曼型邻居
// int dy[4] = {0, 0, 1, -1};
// int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1}; // 摩尔型邻居
// int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};
// 字符串类:模拟规律 -> Greedy -> dp -> kmp || Automation (注意数据量， 先数学后暴力)
// #include<iomanip> cout << fixed <<  setprecision(k) 输出k位精度

// 调试专用
#define debug cout << " ---- ok ---- \n";
template<typename T>
void print(vector<vector<T>> a){
    for (int i = 0; i < a.size(); ++ i){
        for (int j = 0; j < a[i].size(); ++ j) cout << a[i][j] << (j == sz(a[i]) - 1 ? '\n' : ' ');
    }
}
template<typename T>
void print(T *a, int len){
    for (int i = 0; i < len; ++ i) cout << a[i] << " ";
    cout << endl;
}
template<typename T>
void print(T **a, int row, int col){
    for (int i = 0; i < row; ++ i){
        for (int j = 0; j < col; ++ j) cout << a[i][j] << (j == col - 1 ? '\n' : ' ');
    }
}
template<typename T1, typename T2>
void print(const vector<pair<T1, T2>> a){
    for (auto &e: a) cout << "(" << e.first << ", " << e.second << ")\n";
}
template<typename... Args>
void _SHOW_ALL(Args... args){ }
template<typename T, typename... Args>
void _SHOW_ALL(T val, Args... args){
    cout << val << ", ";
    _SHOW_ALL(args...);
}
template<typename T, typename... Args>
void to_brackets(T val, Args... args){
    cout << "(";
    _SHOW_ALL(val, args...);
    cout << ")\n";
}

template<typename... Args>
void wprint(Args... args){ cout << '\n'; }
template<typename T, typename... Args>
void wprint(T val, Args... args){
    cout << val << " ";
    wprint(args...);
}

inline int read(){
    /* 注意假如为 long long 时需要修改 */
    char c = getchar();
    int x = 0, f = 1;
    while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); }
    while (isdigit(c)) x = (x << 3) + (x << 1) + (c^48), c = getchar();
    return f * x;
}
inline LL readl(){
    char c = getchar();
    LL x = 0, f = 1;
    while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); }
    while (isdigit(c)) x = (x << 3) + (x << 1) + (c^48), c = getchar();
    return f * x;
}
void write(int a){
    if (a < 0) putchar('-'), a = -a;
    if (a >= 10) write(a / 10);
    putchar(a % 10 + 48);
}

const int maxn = 5e5 + 50;
map<int, int> block;
int dp[maxn];
void solve(){
    int n; cin >> n;
    string ss; cin >> ss;
    for (int i = 0; i <= n; ++ i) dp[i] = 0;
    PII seg = make_pair(0, 0);
    for (int i = 1; i <= n; ++ i){
        if (ss[i - 1] == '0') {
            dp[i] = dp[i - 1];
            if (seg.first != 0) {
                block[seg.first] = seg.second;
            }
            seg = {0, 0};
        }
        else {
            if (seg.first == 0) seg.second = i;
            ++ seg.first;
            auto iter = block.lower_bound(seg.first);
            if (iter == block.end()){
                dp[i] = dp[i - 1] + i;
            }
            else {
                int pos = (*iter).second, len = (*iter).first;
                // cout << "参数为:";
                // wprint(pos, len, seg.first);
                // cout << "pos为:" << pos << '\n';
                // cout << "x为" << (pos + len + 1 - seg.first) << '\n';
                dp[i] = dp[i - 1] + (i - (pos + len + 1 - seg.first) + 1);
            }
        }
        // cout << "第" << i << "个:" << dp[i] << '\n';
    }
    LL sum = 0;
    for (int i = 1; i <= n; ++ i) sum += dp[i];
    cout << sum << '\n';
}

int main(){
    int t = 1;
    // int t = read();
    while (t--) solve();
    return 0;
}


#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include <bits/stdc++.h>
using namespace std;
#define SORT(A) std::sort(A.begin(), A.end())
#define RSORT(A) std::sort(A.begin(), A.end(), std::greater<>())
#define FR(A, e) for (auto& e : A)
#define show(A) for (auto& e : A) {cout << e << " ";}; cout << endl;
#define within(x,_left,_right) (_left <= x && x <= _right)
#define rwithin(x, _l, _r) (_l < x && x < _r)
#define all(A) A.begin(),A.end()
#define rall(A) (A).rbegin(),(A).rend()
#define lb lower_bound
#define ub upper_bound
#define pb push_back
#define sz(x) ((int)x.size())
#define complete_unique(a) a.erase(unique(a.begin(),a.end()),a.end())
#define bitcnt(x) (__builtin_popcountll(x))
#define fi first
#define se second
#define mst(x, bit) memset(x, bit, sizeof(x))
#define chmax(a, b) a = max(a, b)
#define chmin(a, b) a = min(a, b)
using LL = long long;
using db = double;
using VI = vector<int>;
using VVI = vector<VI>;
using VVVI = vector<VVI>;
using VL = vector<LL>;
using VVL = vector<VL>;
using VVVL = vector<VVL>;
using VS = vector<string>;
const int inf = 0x3f3f3f3f;
const int rinf = 0xc0c0c0c0;
const LL MOD = 1e9 + 7;
const LL LMAX = 0x7fffffffffffffff;
const LL LMIN = 0x8000000000000000;
typedef std::pair<int, int> PII;
typedef std::pair<LL, LL> PLL;
typedef std::pair<int, char> PIC;
// int dx[4] = {1, -1, 0, 0}; // 冯诺依曼型邻居
// int dy[4] = {0, 0, 1, -1};
// int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1}; // 摩尔型邻居
// int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};
// 字符串类:模拟规律 -> Greedy -> dp -> kmp || Automation (注意数据量， 先数学后暴力)
// #include<iomanip> cout << fixed <<  setprecision(k) 输出k位精度

// 调试专用
#define debug cout << " ---- ok ---- \n";
template<typename T>
void print(vector<vector<T>> a){
    for (int i = 0; i < a.size(); ++ i){
        for (int j = 0; j < a[i].size(); ++ j) cout << a[i][j] << (j == sz(a[i]) - 1 ? '\n' : ' ');
    }
}
template<typename T>
void print(T *a, int len){
    for (int i = 0; i < len; ++ i) cout << a[i] << " ";
    cout << endl;
}
template<typename T>
void print(T **a, int row, int col){
    for (int i = 0; i < row; ++ i){
        for (int j = 0; j < col; ++ j) cout << a[i][j] << (j == col - 1 ? '\n' : ' ');
    }
}
template<typename T1, typename T2>
void print(const vector<pair<T1, T2>> a){
    for (auto &e: a) cout << "(" << e.first << ", " << e.second << ")\n";
}
template<typename... Args>
void _SHOW_ALL(Args... args){ }
template<typename T, typename... Args>
void _SHOW_ALL(T val, Args... args){
    cout << val << ", ";
    _SHOW_ALL(args...);
}
template<typename T, typename... Args>
void to_brackets(T val, Args... args){
    cout << "(";
    _SHOW_ALL(val, args...);
    cout << ")\n";
}

template<typename... Args>
void wprint(Args... args){ cout << '\n'; }
template<typename T, typename... Args>
void wprint(T val, Args... args){
    cout << val << " ";
    wprint(args...);
}

inline int read(){
    /* 注意假如为 long long 时需要修改 */
    char c = getchar();
    int x = 0, f = 1;
    while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); }
    while (isdigit(c)) x = (x << 3) + (x << 1) + (c^48), c = getchar();
    return f * x;
}
inline LL readl(){
    char c = getchar();
    LL x = 0, f = 1;
    while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); }
    while (isdigit(c)) x = (x << 3) + (x << 1) + (c^48), c = getchar();
    return f * x;
}
void write(int a){
    if (a < 0) putchar('-'), a = -a;
    if (a >= 10) write(a / 10);
    putchar(a % 10 + 48);
}

const int maxn = 5e5 + 50;
map<int, int> block;
LL dp[maxn];
void solve(){
    int n; cin >> n;
    string ss; cin >> ss;
    for (int i = 0; i <= n; ++ i) dp[i] = 0;
    PII seg = make_pair(0, 0);

    // 维护一个单调栈
    vector<PII> st; // fi -> 大小， se -> 位置 if fi equal 保留最新的

    for (int i = 1; i <= n; ++ i){
        if (ss[i - 1] == '0') {
            dp[i] = dp[i - 1];
            if (seg.first != 0) {
                // block[seg.first] = seg.second;
                while (!st.empty() && seg.first >= st.back().first) st.pop_back();
                st.push_back(seg);
            }
            seg = {0, 0};
        }
        else {
            if (seg.first == 0) seg.second = i;
            ++ seg.first;
            while (!st.empty() && seg.first > st.back().first) st.pop_back();
            if (st.empty()) dp[i] = dp[i - 1] + i;
            else {
                // cout << 1 << endl;
                // int pos = (*iter).second, len = (*iter).first;
                int pos = st.back().second, len = st.back().first;
                // if (i == 3){
                //     cout << "参数为:";
                //     wprint(pos, len, seg.first);
                //     cout << "pos为:" << pos << '\n';
                //     cout << "x为" << (pos + len + 1 - seg.first) << '\n';
                // }
                dp[i] = dp[i - 1] + (i - (pos + len + 1 - seg.first) + 1);
            }
        }
        // cout << "第" << i << "个:" << dp[i] << '\n';
    }
    LL sum = 0;
    for (int i = 1; i <= n; ++ i) sum += dp[i];
    cout << sum << '\n';
}

int main(){
    int t = 1;
    // freopen("input.txt", "r", stdin);
    // int t = read();
    while (t--) solve();
    // fclose(stdin);
    return 0;
}


#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include <bits/stdc++.h>
using namespace std;
#define SORT(A) std::sort(A.begin(), A.end())
#define RSORT(A) std::sort(A.begin(), A.end(), std::greater<>())
#define FR(A, e) for (auto& e : A)
#define show(A) for (auto& e : A) {cout << e << " ";}; cout << endl;
#define within(x,_left,_right) (_left <= x && x <= _right)
#define rwithin(x, _l, _r) (_l < x && x < _r)
#define all(A) A.begin(),A.end()
#define rall(A) (A).rbegin(),(A).rend()
#define lb lower_bound
#define ub upper_bound
#define pb push_back
#define sz(x) ((int)x.size())
#define complete_unique(a) a.erase(unique(a.begin(),a.end()),a.end())
#define bitcnt(x) (__builtin_popcountll(x))
#define fi first
#define se second
#define mst(x, bit) memset(x, bit, sizeof(x))
#define chmax(a, b) a = max(a, b)
#define chmin(a, b) a = min(a, b)
using LL = long long;
using db = double;
using VI = vector<int>;
using VVI = vector<VI>;
using VVVI = vector<VVI>;
using VL = vector<LL>;
using VVL = vector<VL>;
using VVVL = vector<VVL>;
using VS = vector<string>;
const int inf = 0x3f3f3f3f;
const int rinf = 0xc0c0c0c0;
const LL MOD = 1e9 + 7;
const LL LMAX = 0x7fffffffffffffff;
const LL LMIN = 0x8000000000000000;
typedef std::pair<int, int> PII;
typedef std::pair<LL, LL> PLL;
typedef std::pair<int, char> PIC;
// int dx[4] = {1, -1, 0, 0}; // 冯诺依曼型邻居
// int dy[4] = {0, 0, 1, -1};
// int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1}; // 摩尔型邻居
// int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};
// 字符串类:模拟规律 -> Greedy -> dp -> kmp || Automation (注意数据量， 先数学后暴力)
// #include<iomanip> cout << fixed <<  setprecision(k) 输出k位精度

// 调试专用
#define debug cout << " ---- ok ---- \n";
template<typename T>
void print(vector<vector<T>> a){
    for (int i = 0; i < a.size(); ++ i){
        for (int j = 0; j < a[i].size(); ++ j) cout << a[i][j] << (j == sz(a[i]) - 1 ? '\n' : ' ');
    }
}
template<typename T>
void print(T *a, int len){
    for (int i = 0; i < len; ++ i) cout << a[i] << " ";
    cout << endl;
}
template<typename T>
void print(T **a, int row, int col){
    for (int i = 0; i < row; ++ i){
        for (int j = 0; j < col; ++ j) cout << a[i][j] << (j == col - 1 ? '\n' : ' ');
    }
}
template<typename T1, typename T2>
void print(const vector<pair<T1, T2>> a){
    for (auto &e: a) cout << "(" << e.first << ", " << e.second << ")\n";
}
template<typename... Args>
void _SHOW_ALL(Args... args){ }
template<typename T, typename... Args>
void _SHOW_ALL(T val, Args... args){
    cout << val << ", ";
    _SHOW_ALL(args...);
}
template<typename T, typename... Args>
void to_brackets(T val, Args... args){
    cout << "(";
    _SHOW_ALL(val, args...);
    cout << ")\n";
}

template<typename... Args>
void wprint(Args... args){ cout << '\n'; }
template<typename T, typename... Args>
void wprint(T val, Args... args){
    cout << val << " ";
    wprint(args...);
}

inline int read(){
    /* 注意假如为 long long 时需要修改 */
    char c = getchar();
    int x = 0, f = 1;
    while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); }
    while (isdigit(c)) x = (x << 3) + (x << 1) + (c^48), c = getchar();
    return f * x;
}
inline LL readl(){
    char c = getchar();
    LL x = 0, f = 1;
    while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); }
    while (isdigit(c)) x = (x << 3) + (x << 1) + (c^48), c = getchar();
    return f * x;
}
void write(int a){
    if (a < 0) putchar('-'), a = -a;
    if (a >= 10) write(a / 10);
    putchar(a % 10 + 48);
}

const int maxn = 5e5 + 50;
map<int, int> block;
LL dp[maxn];
void solve(){
    int n; cin >> n;
    string ss; cin >> ss;
    for (int i = 0; i <= n; ++ i) dp[i] = 0;
    PII seg = make_pair(0, 0);
    for (int i = 1; i <= n; ++ i){
        if (ss[i - 1] == '0') {
            dp[i] = dp[i - 1];
            if (seg.first != 0) {
                block[seg.first] = seg.second;
            }
            seg = {0, 0};
        }
        else {
            if (seg.first == 0) seg.second = i;
            ++ seg.first;
            auto iter = block.lower_bound(seg.first);
            if (iter == block.end()){
                dp[i] = dp[i - 1] + i;
            }
            else {
                int pos = (*iter).second, len = (*iter).first;
                // cout << "参数为:";
                // wprint(pos, len, seg.first);
                // cout << "pos为:" << pos << '\n';
                // cout << "x为" << (pos + len + 1 - seg.first) << '\n';
                dp[i] = dp[i - 1] + (i - (pos + len + 1 - seg.first) + 1);
            }
        }
        // cout << "第" << i << "个:" << dp[i] << '\n';
    }
    LL sum = 0;
    for (int i = 1; i <= n; ++ i) sum += dp[i];
    cout << sum << '\n';
}

int main(){
    int t = 1;
    // int t = read();
    while (t--) solve();
    return 0;
}


#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include <bits/stdc++.h>
using namespace std;
#define SORT(A) std::sort(A.begin(), A.end())
#define RSORT(A) std::sort(A.begin(), A.end(), std::greater<>())
#define FR(A, e) for (auto& e : A)
#define show(A) for (auto& e : A) {cout << e << " ";}; cout << endl;
#define within(x,_left,_right) (_left <= x && x <= _right)
#define rwithin(x, _l, _r) (_l < x && x < _r)
#define all(A) A.begin(),A.end()
#define rall(A) (A).rbegin(),(A).rend()
#define lb lower_bound
#define ub upper_bound
#define pb push_back
#define sz(x) ((int)x.size())
#define complete_unique(a) a.erase(unique(a.begin(),a.end()),a.end())
#define bitcnt(x) (__builtin_popcountll(x))
#define fi first
#define se second
#define mst(x, bit) memset(x, bit, sizeof(x))
#define chmax(a, b) a = max(a, b)
#define chmin(a, b) a = min(a, b)
using LL = long long;
using db = double;
using VI = vector<int>;
using VVI = vector<VI>;
using VVVI = vector<VVI>;
using VL = vector<LL>;
using VVL = vector<VL>;
using VVVL = vector<VVL>;
using VS = vector<string>;
const int inf = 0x3f3f3f3f;
const int rinf = 0xc0c0c0c0;
const LL MOD = 1e9 + 7;
const LL LMAX = 0x7fffffffffffffff;
const LL LMIN = 0x8000000000000000;
typedef std::pair<int, int> PII;
typedef std::pair<LL, LL> PLL;
typedef std::pair<int, char> PIC;
// int dx[4] = {1, -1, 0, 0}; // 冯诺依曼型邻居
// int dy[4] = {0, 0, 1, -1};
// int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1}; // 摩尔型邻居
// int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};
// 字符串类:模拟规律 -> Greedy -> dp -> kmp || Automation (注意数据量， 先数学后暴力)
// #include<iomanip> cout << fixed <<  setprecision(k) 输出k位精度

// 调试专用
#define debug cout << " ---- ok ---- \n";
template<typename T>
void print(vector<vector<T>> a){
    for (int i = 0; i < a.size(); ++ i){
        for (int j = 0; j < a[i].size(); ++ j) cout << a[i][j] << (j == sz(a[i]) - 1 ? '\n' : ' ');
    }
}
template<typename T>
void print(T *a, int len){
    for (int i = 0; i < len; ++ i) cout << a[i] << " ";
    cout << endl;
}
template<typename T>
void print(T **a, int row, int col){
    for (int i = 0; i < row; ++ i){
        for (int j = 0; j < col; ++ j) cout << a[i][j] << (j == col - 1 ? '\n' : ' ');
    }
}
template<typename T1, typename T2>
void print(const vector<pair<T1, T2>> a){
    for (auto &e: a) cout << "(" << e.first << ", " << e.second << ")\n";
}
template<typename... Args>
void _SHOW_ALL(Args... args){ }
template<typename T, typename... Args>
void _SHOW_ALL(T val, Args... args){
    cout << val << ", ";
    _SHOW_ALL(args...);
}
template<typename T, typename... Args>
void to_brackets(T val, Args... args){
    cout << "(";
    _SHOW_ALL(val, args...);
    cout << ")\n";
}

template<typename... Args>
void wprint(Args... args){ cout << '\n'; }
template<typename T, typename... Args>
void wprint(T val, Args... args){
    cout << val << " ";
    wprint(args...);
}

inline int read(){
    /* 注意假如为 long long 时需要修改 */
    char c = getchar();
    int x = 0, f = 1;
    while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); }
    while (isdigit(c)) x = (x << 3) + (x << 1) + (c^48), c = getchar();
    return f * x;
}
inline LL readl(){
    char c = getchar();
    LL x = 0, f = 1;
    while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); }
    while (isdigit(c)) x = (x << 3) + (x << 1) + (c^48), c = getchar();
    return f * x;
}
void write(int a){
    if (a < 0) putchar('-'), a = -a;
    if (a >= 10) write(a / 10);
    putchar(a % 10 + 48);
}

const int maxn = 5e5 + 50;
map<int, int> block;
LL dp[maxn];
void solve(){
    int n; cin >> n;
    string ss; cin >> ss;
    for (int i = 0; i <= n; ++ i) dp[i] = 0;
    PII seg = make_pair(0, 0);

    // 维护一个单调栈
    vector<PII> st; // fi -> 大小， se -> 位置 if fi equal 保留最新的

    for (int i = 1; i <= n; ++ i){
        if (ss[i - 1] == '0') {
            dp[i] = dp[i - 1];
            if (seg.first != 0) {
                // block[seg.first] = seg.second;
                while (!st.empty() && seg.first >= st.back().first) st.pop_back();
                st.push_back(seg);
            }
            seg = {0, 0};
        }
        else {
            if (seg.first == 0) seg.second = i;
            ++ seg.first;
            while (!st.empty() && seg.first > st.back().first) st.pop_back();
            if (st.empty()) dp[i] = dp[i - 1] + i;
            else {
                // cout << 1 << endl;
                // int pos = (*iter).second, len = (*iter).first;
                int pos = st.back().second, len = st.back().first;
                // if (i == 3){
                //     cout << "参数为:";
                //     wprint(pos, len, seg.first);
                //     cout << "pos为:" << pos << '\n';
                //     cout << "x为" << (pos + len + 1 - seg.first) << '\n';
                // }
                dp[i] = dp[i - 1] + (i - (pos + len + 1 - seg.first) + 1);
            }
        }
        // cout << "第" << i << "个:" << dp[i] << '\n';
    }
    LL sum = 0;
    for (int i = 1; i <= n; ++ i) sum += dp[i];
    cout << sum << '\n';
}

int main(){
    int t = 1;
    freopen("input.txt", "r", stdin);
    // int t = read();
    while (t--) solve();
    fclose(stdin);
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template <class T> ll size(const T &x) { return x.size(); }
#define rep(i,a,b) for(ll i = (a); i < (b); i++)
#define iter(it,c) for(auto it = (c).begin(); it != (c).end();++it)
#define pb push_back
#define fs first
#define sc second
typedef pair<ll,ll> ii;
typedef vector<ll> vi;
typedef vector<ii> vii;

const ll INF = ~(1<<31);
const double pi = acos(-1);
const double EPS = 1e-9;
typedef pair<ii,ii> i4;

struct node {
	node* left = NULL;
	node* right = NULL;
	int atl, atr, val;
	int lazy = 0;
	node(node* l, node* r, int v, int al, int ar) {
		left = l; right = r; val = v;
		atl = al; atr = ar;
	}
	void lazyupdate(int l, int r, int by) {
		if(lazy != 0) propagate();
		if(l > atr || r < atl) return;
		if(l <= atl && atr <= r) {
			val += (atr-atl+1)*by;
			if(left != NULL) {
				left->lazy += by;
				right->lazy += by;
			}
			return;
		}
		left->lazyupdate(l,r,by);
		right->lazyupdate(l,r,by);
		val = left->val+right->val;
	}
	int lazyquery(int l, int r) {
		if(l > atr || r < atl) return 0;
		if(lazy != 0) propagate();
		if(l <= atl && atr <= r) return val;
		return left->lazyquery(l,r)+right->lazyquery(l,r);
	}
	void propagate() {
		val += (atr-atl+1)*lazy;
		if(left != NULL) {
			right->lazy += lazy;
			left->lazy += lazy;
		}
		lazy = 0;
	}
};

node* build(int l, int r) {
	if(l > r) return NULL;
	if(l == r) return new node(NULL, NULL, 0, l, r);
	int m = (l+r)/2;
	node* left = build(l,m);
	node* right = build(m+1,r);
	node* cur = new node(left,right,0,l,r);
	return cur;
}

int main() {
    cin.sync_with_stdio(false);
    int n;
    cin >> n;

    string s;
    cin >> s;

    node* root = build(0,n-1);
    ll tts = 0;
    int cur = 0;
    rep(i,0,n) {
        if(s[i] == '0') cur = 0;
        else cur++;
        if(cur == 0) {
            tts += root->lazyquery(0,n-1);
            continue;
        }
        int lo = 0, hi = i;
        int bst = 0;
        int look = cur;
        while(lo <= hi) {
            int mid = (lo+hi)/2;
            if(root->lazyquery(mid,mid) < look) {
                bst = mid;
                hi = mid-1;
            } else {
                lo = mid+1;
            }
        }
        root->lazyupdate(bst,i,1);
        tts += root->lazyquery(0,n-1);
    }
    cout << tts << endl;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template <class T> ll size(const T &x) { return x.size(); }
#define rep(i,a,b) for(ll i = (a); i < (b); i++)
#define iter(it,c) for(auto it = (c).begin(); it != (c).end();++it)
#define pb push_back
#define fs first
#define sc second
typedef pair<ll,ll> ii;
typedef vector<ll> vi;
typedef vector<ii> vii;

const ll INF = ~(1<<31);
const double pi = acos(-1);
const double EPS = 1e-9;
typedef pair<ii,ii> i4;

struct node {
	node* left = NULL;
	node* right = NULL;
	ll atl, atr, val;
	ll lazy = 0;
	node(node* l, node* r, ll v, ll al, ll ar) {
		left = l; right = r; val = v;
		atl = al; atr = ar;
	}
	void lazyupdate(ll l, ll r, ll by) {
		if(lazy != 0) propagate();
		if(l > atr || r < atl) return;
		if(l <= atl && atr <= r) {
			val += (atr-atl+1)*by;
			if(left != NULL) {
				left->lazy += by;
				right->lazy += by;
			}
			return;
		}
		left->lazyupdate(l,r,by);
		right->lazyupdate(l,r,by);
		val = left->val+right->val;
	}
	ll lazyquery(ll l, ll r) {
		if(l > atr || r < atl) return 0;
		if(lazy != 0) propagate();
		if(l <= atl && atr <= r) return val;
		return left->lazyquery(l,r)+right->lazyquery(l,r);
	}
	void propagate() {
		val += (atr-atl+1)*lazy;
		if(left != NULL) {
			right->lazy += lazy;
			left->lazy += lazy;
		}
		lazy = 0;
	}
};

node* build(ll l, ll r) {
	if(l > r) return NULL;
	if(l == r) return new node(NULL, NULL, 0, l, r);
	ll m = (l+r)/2;
	node* left = build(l,m);
	node* right = build(m+1,r);
	node* cur = new node(left,right,0,l,r);
	return cur;
}

int main() {
    cin.sync_with_stdio(false);
    ll n;
    cin >> n;

    string s;
    cin >> s;

    node* root = build(0,n-1);
    ll tts = 0;
    ll cur = 0;
    rep(i,0,n) {
        if(s[i] == '0') cur = 0;
        else cur++;
        if(cur == 0) {
            tts += root->lazyquery(0,n-1);
            continue;
        }
        ll lo = 0, hi = i;
        ll bst = 0;
        ll look = cur;
        while(lo <= hi) {
            ll mid = (lo+hi)/2;
            if(root->lazyquery(mid,mid) < look) {
                bst = mid;
                hi = mid-1;
            } else {
                lo = mid+1;
            }
        }
        root->lazyupdate(bst,i,1);
        tts += root->lazyquery(0,n-1);
    }
    cout << tts << endl;
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(auto i = (a); i < (b); i++)
#define pb push_back
#define fs first
#define sc second
typedef long long ll;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ii> vii;
typedef vector<vii> vvii;

const double EPS = 1e-9;
struct node {
	node* left = NULL;
	node* right = NULL;
	int atl, atr, val;
	int lazy = 0;
    int lazy_set = 0;
	int mn,mx;
	node(node* l, node* r, int v, int al, int ar) {
		left = l; right = r; val = v;
		atl = al; atr = ar; mn = v; mx = v;
	}
	void lazyupdate(int l, int r, int by) {
		if(lazy != 0 || lazy_set != 0) propagate();
		if(l > atr || r < atl) return;
		if(l <= atl && atr <= r) {
			val += (atr-atl+1)*by;
			mx += by; mn += by;
			if(left != NULL) {
				left->lazy += by;
				right->lazy += by;
			}
			return;
		}
		left->lazyupdate(l,r,by);
		right->lazyupdate(l,r,by);
		mn = min(left->mn, right->mn);
		mx = max(left->mx, right->mx);
		val = left->val+right->val;
	}
	void lazyset(int l, int r, int by) {
		if(lazy != 0 || lazy_set != 0) propagate();
		if(l > atr || r < atl) return;
		if(l <= atl && atr <= r) {
			val = (atr-atl+1)*by;
			mx = by; mn = by;
			if(left != NULL) {
                left->lazy = 0;
                right->lazy = 0;
				left->lazy_set = by;
				right->lazy_set = by;
			}
			return;
		}
		left->lazyset(l,r,by);
		right->lazyset(l,r,by);
		mn = min(left->mn, right->mn);
		mx = max(left->mx, right->mx);
		val = left->val+right->val;
	}
	int lazyquery(int l, int r) {
		if(l > atr || r < atl) return 0;
		if(lazy != 0) propagate();
		if(l <= atl && atr <= r) return val;
		return left->lazyquery(l,r)+right->lazyquery(l,r);
	}
	void propagate() {
		val = (atr-atl+1)*lazy_set;
        val += (atr-atl+1)*lazy;
		if(left != NULL) {
			right->lazy += lazy;
			left->lazy += lazy;
			right->lazy_set += lazy_set;
			left->lazy_set += lazy_set;
		}
		lazy = 0;
	}
};

node* build(int l, int r) {
	if(l > r) return NULL;
	if(l == r) return new node(NULL, NULL, 0, l, r);
	int m = (l+r)/2;
	node* left = build(l,m);
	node* right = build(m+1,r);
	node* cur = new node(left,right,0,l,r);
	return cur;
}

int n;
string s;
ll total = 0;
node* root;

ll sweet(int l, int r) {
    ll tots = 0;
    rep(j,l,r+1) {
        rep(z,j,r+1) {
            int start = j;
            int to = z;
            int bst = 0;
            int cur = 0;
            rep(k,start,to+1) {
                if(s[k] == '1') cur++;
                else cur = 0;
                bst = max(bst, cur);
            }
            tots += bst;
        }
    }
    return tots;
}

ll solve(int l, int r) {
    if(l > r) return 0;
    if(l == r) {
        if(s[l] == '1') return 1;
        return 0;
    }
    ll cursm = 0;

    root->lazyset(l,r,0);
    int mid = (l+r)/2;
    int mx = 0;
    int tots = 0;
    for(int i = mid; i >= l; i--) {
        if(s[i] == '1') {
            tots++;
        } else if(s[i] == '0') {
            tots = 0;
        }
        mx = max(mx, tots);
        root->lazyset(i,i,mx);
    }
    cursm += root->lazyquery(l,mid);

    int cur = 0;
    for(int i = mid; i >= l; i--) {
        if(s[i] == '1') cur++;
        else break;
    }
    for(int i = mid+1; i <= r; i++) {
        if(s[i] == '1') {
            cur++;
        } else if(s[i] == '0') {
            cur = 0;
        }
        int lo = l, hi = i-cur;
        int bst = -1;
        while(lo <= hi) {
            int lel = (lo+hi)/2;
            if(root->lazyquery(lel,lel) < cur) {
                hi = lel-1;
                bst = lel;
            } else {
                lo = lel+1;
            }
        }
        if(bst != -1) {
            root->lazyset(bst, i-cur, cur);
        }
        if(s[i] == '1') {
            root->lazyupdate(i-cur+1,i,1);
        }
        cursm += root->lazyquery(l,mid);

    }

    cursm += solve(l,mid-1);
    cursm += solve(mid+1,r);
    return cursm;
}

int main() {
    cin.sync_with_stdio(false);
    cin >> n;
    cin >> s;
    root = build(0,n+10);
    cout << solve(0,n-1) << endl;
}


//#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<math.h>
#include<numeric>
#include<deque>
#include<map>
#include<set>
#include<queue>
#include<optional>
#include<assert.h>
#include<tuple>
#include<list>
#include<deque>
#include<functional>

using namespace std;

void solve() {
	int n;
	cin >> n;
	vector<int64_t> calc(n + 1,0);
	for (int64_t i = 1; i < calc.size(); ++i) {
		calc[i] = calc[i - 1] + (i + 1) * i / 2;
	}
	string given;
	cin >> given;
	multimap<int, pair<int, int>,greater<int>> abl_seg;
	int64_t result = 0;
	auto it = find(given.begin(), given.end(), '1');
	while (it != given.end()) {
		auto org = find(it, given.end(), '0');
		abl_seg.insert({ org - it,{it - given.begin(),org - given.begin()} });
		result += calc[org - it];
		it = find(org, given.end(), '1');
	}
	set<int> seg_begin = {0};
	set<int> seg_end = {n};
	while (!abl_seg.empty()) {
		int len = abl_seg.begin()->first;
		pair<int, int> seg = abl_seg.begin()->second;
		abl_seg.erase(abl_seg.begin());
		int cur_beg = *(--seg_begin.upper_bound(seg.first));
		int cur_end = *seg_end.lower_bound(seg.second);
		int64_t left = seg.first - cur_beg + 1;
		int64_t right = cur_end - seg.second + 1;

		result += left * right * len - len;
		if (left > 1 && len > 1) {
			abl_seg.insert({ len - 1,{seg.first,seg.second - 1} });
		}
		if (right > 1 && len > 1) {
			abl_seg.insert({ len - 1,{seg.first + 1,seg.second} });
		}

		seg_begin.insert(seg.first + 1);
		seg_end.insert(seg.second - 1);
	}
	cout << result;
	return;

}

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int t = 1;
	//cin >> t;
	while (t--)solve();
	return 0;
}


//#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<math.h>
#include<numeric>
#include<deque>
#include<map>
#include<set>
#include<queue>
#include<optional>
#include<assert.h>
#include<tuple>
#include<list>
#include<deque>

using namespace std;

void solve() {
	int n;
	cin >> n;
	vector<int64_t> calc(n + 1,0);
	for (int64_t i = 1; i < calc.size(); ++i) {
		calc[i] = calc[i - 1] + (i + 1) * i / 2;
	}
	string given;
	cin >> given;
	multimap<int, pair<int, int>,greater<int>> abl_seg;
	int64_t result = 0;
	auto it = find(given.begin(), given.end(), '1');
	while (it != given.end()) {
		auto org = find(it, given.end(), '0');
		abl_seg.insert({ org - it,{it - given.begin(),org - given.begin()} });
		result += calc[org - it];
		it = find(org, given.end(), '1');
	}
	set<int> seg_begin = {0};
	set<int> seg_end = {n};
	while (!abl_seg.empty()) {
		int len = abl_seg.begin()->first;
		pair<int, int> seg = abl_seg.begin()->second;
		abl_seg.erase(abl_seg.begin());
		int cur_beg = *(--seg_begin.upper_bound(seg.first));
		int cur_end = *seg_end.lower_bound(seg.second);
		int64_t left = seg.first - cur_beg + 1;
		int64_t right = cur_end - seg.second + 1;

		result += left * right * len - len;
		if (left > 1 && len > 1) {
			abl_seg.insert({ len - 1,{seg.first,seg.second - 1} });
		}
		if (right > 1 && len > 1) {
			abl_seg.insert({ len - 1,{seg.first + 1,seg.second} });
		}

		seg_begin.insert(seg.first + 1);
		seg_end.insert(seg.second - 1);
	}
	cout << result;
	return;

}

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int t = 1;
	//cin >> t;
	while (t--)solve();
	return 0;
}


#include <algorithm>
#include <cassert>
#include <iomanip>
#include <istream>
#include <map>
#include <numeric>
#include <ostream>
#include <set>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
// Powered by caide (code generator, tester, and library code inliner)

class Input {
public:
  std::vector<long long> groups;
};

Input read_input(std::istream &in) {
  long long n;
  in >> n;
  std::string s;
  in >> s;
  long long cur_group = 0;
  Input out;
  auto cur_char = '0';
  for (auto c : s) {
    if (c != cur_char)
      {
        out.groups.push_back(cur_group);
        cur_group = 1;
        cur_char = (cur_char == '1' ? '0' : '1');
      }
    else
      ++cur_group;
  }
  out.groups.push_back(cur_group);
  return out;
}

long long solve (const Input &input)
{
   std::vector<long long> sums;
   long long summand = 0;
   long long sum = 0;
   bool is_empty = true;
   for (auto cur_group : input.groups)
     {
       for (long long num = 1; num <= cur_group; ++num)
         {
           auto contrib = num;
            if (is_empty)
              contrib = 0;
           if (sums.size () < contrib + 1)
             sums.resize (contrib + 1);
           ++sums[contrib];
           summand += contrib;
           if (contrib > 0)
             {
               auto transferred = contrib == 1 ? sums[contrib - 1] : sums[contrib - 1] - 1;
               sums[contrib - 1] -= transferred;
               sums[contrib] += transferred;
               summand += transferred;
             }
           sum += summand;
         }
       is_empty = !is_empty;
     }
  return sum;
}

class Solution {
public:
  void solve(std::istream &in, std::ostream &out)
  {
    out << ::solve (read_input(in)) << '\n';
  }
};

void solve(std::istream &in, std::ostream &out) {
  out << std::setprecision(12);
  Solution solution;
  solution.solve(in, out);
}

#include <fstream>
#include <iostream>

int main() {

    ios_base::sync_with_stdio(false);
    cin.tie(0);

    istream& in = cin;

    ostream& out = cout;

    solve(in, out);
    return 0;
}


#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <array>
#include <stdint.h>
#include <set>
#include <unordered_map>
#include <map>
#include <bitset>
#include <string>
#include <cmath>
#include <queue>
#include <iterator>
#include <xutility>
#include <iomanip>
#include <numeric>
//#include "dmSegmentTree.hpp"
#include <xstddef>
#include <random>
#include <functional>

using namespace std;

#define ALL(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define per(i,a,b) for(int i=(a);i>=(b);--i)
#define forn(i, n) for(int i = 0; i < int(n); i++)

template <class T>
vector<T> ReadVec(const int count)
{
	vector<T> res(count);
	forn(i, count)
	{
		std::cin >> res[i];
	}
	return res;
}

template <class T>
void PrintVecOneLine(const vector<T>& src)
{
	forn(i, src.size())
	{
		std::cout << src[i];
		if (i + 1 != src.size())
			std::cout << " ";
	}
	std::cout << "\n";
}

template <class T>
void PrintVecManyLine(const vector<T>& src)
{
	forn(i, src.size())
	{
		std::cout << src[i] << "\n";
	}
}

std::vector<std::vector<int>> BuildGraph(int n,int m, bool oriented, int inc = 1)
{
	std::vector<std::vector<int>> res(n);
	forn(i, m)
	{
		int a, b;
		std::cin >> a >> b;
		res[a - inc].push_back(b - inc);
		if (oriented)
			continue;
		res[b - inc].push_back(a - inc);
	}
	return res;
}

std::vector<std::vector<int>> BuildGraph(
	int n,int m, bool oriented, std::vector<int64_t>& weight, int inc = 1)
{
	std::vector<std::vector<int>> res(n);
	weight.resize(m);
	forn(i, m)
	{
		int a, b;
		std::cin >> a >> b >> weight[i];
		res[a - inc].push_back(b - inc);
		if (oriented)
			continue;
		res[b - inc].push_back(a - inc);
	}
	return res;
}

//int64_t inf = std::numeric_limits<int64_t>::max();

//#define HOME
// BABB A
// BA BABB B
// (a^2 + b^2) - 2ab== (a + b)^2
// sum = a^2 + b^2 + c^2

struct comp
{
	bool operator()(const std::pair<int64_t, int64_t>& a, const std::pair<int64_t, int64_t>& b) const
	{
		return a.first < b.first;
	}
};
int main()
{
#ifdef HOME
	freopen("input.txt", "r", stdin);
#else
	std::ios_base::sync_with_stdio(0); std::cin.tie(0); std::cout.tie(0);
	std::cout.setf(std::ios::fixed); std::cout.precision(20);
#endif
	int64_t n;
	cin >> n;
	auto touchCount = ReadVec<int>(n);
	std::array<std::vector<int>, 4> positions;
	for (int i = 0; i < touchCount.size(); ++i)
	{
		positions[touchCount[i]].push_back(i);
	}
	std::vector<std::pair<int, int>> rc;
	std::map<int, int> allPosYForThree;
	for (int i = 0; i < n; ++i)
	{
		allPosYForThree[i] = 0;
	}

	std::map<int, int> allPosXForThree;
	std::map<int, int> allPosXForThree2;

	int startY = n - 1;
	for (int i = 1; i < 4; ++i)
	{
		if (i == 3)
		{
			allPosXForThree.insert(allPosXForThree2.begin(), allPosXForThree2.end());
		}
		for (auto pos = positions[i].rbegin(); pos != positions[i].rend(); ++pos)
		{
			if (i == 1)
			{
				rc.emplace_back(*pos, startY);
				allPosXForThree.emplace(*pos, startY);
				allPosYForThree.erase(allPosYForThree.find(startY));
				--startY;
			}
			if (i == 2)
			{
				if (allPosXForThree.empty())
				{
					cout << "-1\n";
					return 0;
				}
				else
				{
					auto found = allPosXForThree.rbegin();
					if (found->first < *pos)
					{
						cout << "-1\n";
						return 0;
					}
					rc.emplace_back(*pos, found->second);
					int yl = found->second;
					allPosXForThree.erase(std::prev(allPosXForThree.end()));
					allPosXForThree2[*pos] = yl;
					//allPosXForThree[*pos] = yl;
				}
			}
			if (i == 3)
			{
				if (allPosXForThree.empty() || allPosYForThree.empty())
				{
					cout << "-1\n";
					return 0;
				}
				else
				{
					auto found = allPosXForThree.rbegin();
					if (found->first < *pos)
					{
						cout << "-1\n";
						return 0;
					}
					auto foundY = allPosYForThree.rbegin();
					rc.emplace_back(*pos, foundY->first);
					rc.emplace_back(found->first, foundY->first);
					allPosYForThree.erase(std::prev(allPosYForThree.end()));
				}
			}
			if (startY < 0)
			{
				cout << "-1\n";
				return 0;
			}
		}

	}
	std::cout << rc.size()<< endl;
	for (auto pr : rc)
	{
		cout << pr.second + 1 << " " << pr.first + 1 << endl;
	}

	return 0;
}


#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <array>
#include <stdint.h>
#include <set>
#include <unordered_map>
#include <map>
#include <bitset>
#include <string>
#include <cmath>
#include <queue>
#include <iterator>
#include <xutility>
#include <iomanip>
#include <numeric>
#include "dmSegmentTree.hpp"
#include <xstddef>
#include <random>
#include <functional>

using namespace std;

#define ALL(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define per(i,a,b) for(int i=(a);i>=(b);--i)
#define forn(i, n) for(int i = 0; i < int(n); i++)

template <class T>
vector<T> ReadVec(const int count)
{
	vector<T> res(count);
	forn(i, count)
	{
		std::cin >> res[i];
	}
	return res;
}

template <class T>
void PrintVecOneLine(const vector<T>& src)
{
	forn(i, src.size())
	{
		std::cout << src[i];
		if (i + 1 != src.size())
			std::cout << " ";
	}
	std::cout << "\n";
}

template <class T>
void PrintVecManyLine(const vector<T>& src)
{
	forn(i, src.size())
	{
		std::cout << src[i] << "\n";
	}
}

std::vector<std::vector<int>> BuildGraph(int n,int m, bool oriented, int inc = 1)
{
	std::vector<std::vector<int>> res(n);
	forn(i, m)
	{
		int a, b;
		std::cin >> a >> b;
		res[a - inc].push_back(b - inc);
		if (oriented)
			continue;
		res[b - inc].push_back(a - inc);
	}
	return res;
}

std::vector<std::vector<int>> BuildGraph(
	int n,int m, bool oriented, std::vector<int64_t>& weight, int inc = 1)
{
	std::vector<std::vector<int>> res(n);
	weight.resize(m);
	forn(i, m)
	{
		int a, b;
		std::cin >> a >> b >> weight[i];
		res[a - inc].push_back(b - inc);
		if (oriented)
			continue;
		res[b - inc].push_back(a - inc);
	}
	return res;
}

//int64_t inf = std::numeric_limits<int64_t>::max();

//#define HOME
// BABB A
// BA BABB B
// (a^2 + b^2) - 2ab== (a + b)^2
// sum = a^2 + b^2 + c^2

struct comp
{
	bool operator()(const std::pair<int, int>& a, const std::pair<int, int>& b) const
	{
		return std::abs(a.first - a.second) < std::abs(b.first - b.second);
	}
};
int main()
{
#ifdef HOME
	freopen("input.txt", "r", stdin);
#else
	std::ios_base::sync_with_stdio(0); std::cin.tie(0); std::cout.tie(0);
	std::cout.setf(std::ios::fixed); std::cout.precision(20);
#endif
	int n;
	cin >> n;
	string s;
	cin >> s;
	int count = 0;
	int fIndx = n;
	std::vector<int64_t> sum(n, 0);
	std::vector<int64_t> ariph(n, 0);

	std::set<std::pair<int, int>, comp> maxInt;
	int64_t res = 0;
	for (int i = 1; i < n; ++i)
	{
		ariph[i] = ariph[i - 1] + i;
	}
	int lastRes = 0;
	for (int i = n-1; i>=0; --i)
	{
		if (s[i] == '1' && count == 0)
		{
			fIndx = i;
			++count;
		}
		if (s[i] == '1')
		{
			auto found = maxInt.upper_bound(std::make_pair(i, fIndx));
			if (found == maxInt.end())
			{
				int c = (n - 1 - fIndx + 1);
				sum[i] = ariph[std::abs(fIndx - i)] + c * (std::abs(fIndx - i) + 1);
				res += ariph[std::abs(fIndx - i)]  + c * (std::abs(fIndx- i) + 1);
			}
			else
			{
				int c = (found->first + std::abs(fIndx - i) - fIndx + 1);
				sum[i] = ariph[std::abs(fIndx - i)] + sum[found->first]
					- ariph[std::abs(fIndx - i) + 1] + c * (std::abs(fIndx - i) + 1);
				res += sum[i];
			}
			++count;
		}
		else
		{
			if (fIndx != n)
			{
				maxInt.emplace(i + 1, fIndx);
				fIndx = n;
				lastRes = sum[i+1];
			}
			res += lastRes;
			count = 0;
		}

	}
	std::cout << res<< std::endl;

	return 0;
}


#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <array>
#include <stdint.h>
#include <set>
#include <unordered_map>
#include <map>
#include <bitset>
#include <string>
#include <cmath>
#include <queue>
#include <iterator>
#include <xutility>
#include <iomanip>
#include <numeric>
//#include "dmSegmentTree.hpp"
#include <xstddef>
#include <random>
#include <functional>

using namespace std;

#define ALL(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define per(i,a,b) for(int i=(a);i>=(b);--i)
#define forn(i, n) for(int i = 0; i < int(n); i++)

template <class T>
vector<T> ReadVec(const int count)
{
	vector<T> res(count);
	forn(i, count)
	{
		std::cin >> res[i];
	}
	return res;
}

template <class T>
void PrintVecOneLine(const vector<T>& src)
{
	forn(i, src.size())
	{
		std::cout << src[i];
		if (i + 1 != src.size())
			std::cout << " ";
	}
	std::cout << "\n";
}

template <class T>
void PrintVecManyLine(const vector<T>& src)
{
	forn(i, src.size())
	{
		std::cout << src[i] << "\n";
	}
}

std::vector<std::vector<int>> BuildGraph(int n,int m, bool oriented, int inc = 1)
{
	std::vector<std::vector<int>> res(n);
	forn(i, m)
	{
		int a, b;
		std::cin >> a >> b;
		res[a - inc].push_back(b - inc);
		if (oriented)
			continue;
		res[b - inc].push_back(a - inc);
	}
	return res;
}

std::vector<std::vector<int>> BuildGraph(
	int n,int m, bool oriented, std::vector<int64_t>& weight, int inc = 1)
{
	std::vector<std::vector<int>> res(n);
	weight.resize(m);
	forn(i, m)
	{
		int a, b;
		std::cin >> a >> b >> weight[i];
		res[a - inc].push_back(b - inc);
		if (oriented)
			continue;
		res[b - inc].push_back(a - inc);
	}
	return res;
}

//int64_t inf = std::numeric_limits<int64_t>::max();

//#define HOME
// BABB A
// BA BABB B
// (a^2 + b^2) - 2ab== (a + b)^2
// sum = a^2 + b^2 + c^2

struct comp
{
	bool operator()(const std::pair<int, int>& a, const std::pair<int, int>& b) const
	{
		return std::abs(a.first - a.second) < std::abs(b.first - b.second);
	}
};
int main()
{
#ifdef HOME
	freopen("input.txt", "r", stdin);
#else
	std::ios_base::sync_with_stdio(0); std::cin.tie(0); std::cout.tie(0);
	std::cout.setf(std::ios::fixed); std::cout.precision(20);
#endif
	int n;
	cin >> n;
	string s;
	cin >> s;
	int count = 0;
	int fIndx = n;
	std::vector<int64_t> sum(n, 0);
	std::vector<int64_t> ariph(n, 0);

	std::set<std::pair<int, int>, comp> maxInt;
	int64_t res = 0;
	for (int i = 1; i < n; ++i)
	{
		ariph[i] = ariph[i - 1] + i;
	}
	int lastRes = 0;
	for (int i = n-1; i>=0; --i)
	{
		if (s[i] == '1' && count == 0)
		{
			fIndx = i;
			++count;
		}
		if (s[i] == '1')
		{
			auto found = maxInt.upper_bound(std::make_pair(i, fIndx));
			if (found == maxInt.end())
			{
				int c = (n - 1 - fIndx + 1);
				sum[i] = ariph[std::abs(fIndx - i)] + c * (std::abs(fIndx - i) + 1);
				res += ariph[std::abs(fIndx - i)]  + c * (std::abs(fIndx- i) + 1);
			}
			else
			{
				int c = (found->first + std::abs(fIndx - i) - fIndx + 1);
				sum[i] = ariph[std::abs(fIndx - i)] + sum[found->first]
					- ariph[std::abs(fIndx - i) + 1] + c * (std::abs(fIndx - i) + 1);
				res += sum[i];
			}
			++count;
		}
		else
		{
			if (fIndx != n)
			{
				maxInt.emplace(i + 1, fIndx);
				fIndx = n;
				lastRes = sum[i+1];
			}
			res += lastRes;
			count = 0;
		}

	}
	std::cout << res<< std::endl;

	return 0;
}