t = int(input())
for game in range(t):
    x = int(input())
    val = 1
    power = 2
    count = 0
    while val <= x:
        count += 1
        x -= val
        val = 2 * val + power**2
        power *= 2
    print(count)


t = int(input())
for game in range(t):
    x = int(input())
    num = 0
    nums = []
    for n in range(50):
        num += 2**n
        nums.append(num)
    x_needed = [(n**2 + n)/2 for n in nums]
    i = 0
    while x > 0:
        x -= x_needed[i]
        if x >= 0:
            i += 1
    print(i)


for _ in range(int(input())):
    x=int(input());i=-1
    while x>=0:i+=1;k=2**i-1;x-=k(k+1)/2
    print(i)


t = int(input())
for _ in range(t):
    n = int(input())
    k = 1
    ans = 0
    while n >= k*(k+1)/2:
        n -= k*(k+1)/2
        ans += 1
        k = k*2 + 1
    print(ans)


for _ in range(int(input())):
    x=int(input());i=-1
    while x>=0:i+=1;k=2**i;x-=2*k*k-k
    print(i)


for _ in range(int(input())):
    x=int(input())
    i=-1
    while x>=0:
        i+=1
        k=(2**i)-1
        x-=k*(k+1)/2
    print(i)


for _ in range(int(input())):
    x=int(input())
    i=-1
    while x>=0:
        i+=1
        k=(2**i)-1
        x-=k(k+1)/2
    print(i)


for _ in range(int(input())):
    x=int(input())
    i=-1
    while x>=0:
        i+=1
        k=(2**i)-1
        x-=k*(k+1)//2
    print(i-1)


for _ in range(int(input())):
    x=int(input())
    i=-1
    while x>=0:
        i+=1
        k=(2**i)-1
        x-=k*(k+1)/2
    print(i-1)


for t in range(int(input())):
    x=int(input())
    n=1
    ans=0
    while x+x>=n*(n+1):
        x-=(n*(n+1))/2
        ans+=1
        n=n+n+1
    print(ans)


t = int(input())
for _ in range(t):
    n = int(input())
    k = 1
    ans = 0
    sum = 0
    while sum <= n:
        sum += k*(k+1)/2
        ans += 1
        k = k*2 + 1
    print(ans-1)


t = int(input())
for _ in range(t):
    n = int(input())
    k = 1
    ans = 0
    sum = 0
    while sum <= n:
        sum += k*(k+1)/2
        ans += 1
        k = 2**(ans+1) -1
    print(ans-1)


t = int(input())
for _ in range(t):
    n = int(input())
    k = 1
    pow2 = 2
    ans = 0
    while n >= k*(k+1)/2:
        n -= k*(k+1)/2
        ans += 1
        k += pow2
        pow2 *= 2
    print(ans)


t = int(input())
for _ in range(t):
    n = input()
    k = 1
    ans = 0
    while 2 * n >= k*(k+1):
        n -= (k*(k+1))/2
        ans += 1
        k = k*2 + 1
    print(ans)


t = int(input())
for _ in range(t):
    n = int(input())
    k = 1
    ans = 0
    while 2 * n >= k*(k+1):
        n -= (k*(k+1))/2
        ans += 1
        k = k*2 + 1
    print(ans)


import sys
import math

# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')

input = sys.stdin.readline
sizes = [2**i - 1 for i in range(1, 32)]
blocks = [(size * (size + 1)) // 2 for size in sizes]

t = int(input())
for x in range(t):
	x = int(input())
	i = 0
	while x >= blocks[i]:
		x -= blocks[i]
		i += 1
	print(i)


t=int(input())
for i in range(t):
  x=int(input())

  num=0
  total=0
  ans=0
  while True:
    t_total=num*2+(2**ans)**2
    if total+t_total>x:
      print(ans)
      break
    else:
      num=t_total
      total+=t_total
      ans+=1


from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from bisect import bisect_right

t=int(input())
for i in range(t):
  x=int(input())

  ok=1
  ng=x
  while abs(ng-ok)>1:
    m=(ok+ng)//2
    num=2*m*(m+1)*(2*m+1)//6-m*(m+1)//2
    if num<=x:
      ok=m
    else:
      ng=m

  print(ok)


for f in range(int(input())):
    n = int(input())
    i = 1
    j = i
    cnt = j - 1
    while i <= n:
        cnt = cnt + 1
        j = 2 * j
        i = i + ((j + 1) * (j + 2)) // 2
        j = j + 1
    print (cnt)


for f in range(int(input())):
    n = int(input())
    i = 1
    j = i
    ans = i - 1
    while i <= n:
        ans = ans + 1
        j = 2 * j
        i+=((j + 1) * (j + 2)) // 2
    print(ans)


import math

t = int(input())
arr = []

for i in range(t):
    arr.append(int(input()))

k = 0

nice_nums = []
req_squares = []
n = 1

while(True):
    val = 2**n - 1
    nice_nums.append(val)
    req = (val*(val+1))//2
    if(req<=10**18):
        req_squares.append(req)
    else:
        break

    n+=1

for i in range(len(arr)):
    max_cells = arr[i]
    ct = 0
    ans = 0
    for j in range(len(req_squares)):
        ct+=req_squares[j]
        if(ct<=max_cells):
            ans+=1

        else:
            break

    print(ans)


import math

t = int(input())
arr = []

for i in range(t):
    arr.append(int(input()))

k = 0

nice_nums = []
req_squares = []
n = 1

while(True):
    val = 2**n - 1
    nice_nums.append(val)
    req = (val*(val+1))/2
    if(req<=10**18):
        req_squares.append(req)
    else:
        break

    n+=1

for i in range(len(arr)):
    max_cells = arr[i]
    ct = 0
    ans = 0
    for j in range(len(req_squares)):
        ct+=req_squares[j]
        if(ct<=max_cells):
            ans+=1

        else:
            break

    print(ans)


for t in range(int(input())):
    n=int(input())
    c,a,i=0,1,1
    while(n>=a*i):
        n-=(a*i)
        i=i*2
        a+=i
        c+=1
    print(c)


for ca in range(0,int(input)):

    n=int(input())

    tot=0

    for i in range(0,101):
        m=(2**i)-1
        w=(m+1)*m//2

        if w<=n:
            n-=w
            t=t+1
        else:
            break

    print(t-1)

    if 1<2:
        for j in range(m,w):
            t=t-1
            w=w-m


for ca in range(0,int(input)):

    n=int(input())

    tot=0

    for i in range(0,101):
        m=(2**i)-1
        w=(m+1)*m//2

        if w<=n:
            n-=w
            t=t+1
        else:
            break

    print(t-1)

    if 1>2:
        for j in range(m,w):
            t=t-1
            w=w-m


mem ={}

def dp(pos,k):
    if k==1:
       return int(s[0:pos])

    if (pos,k) in mem:
        return mem[(pos,k)]

    res=0
    for x in range(k-1,pos):
        res=max(res,dp(x,k-1) * int (s[x:pos]))

    mem[(pos,k)]=res

    return res

for ca in range(0,int(input())):

    n=int(input())

    tot=0

    for i in range(0,101):
        m=(2**i)-1
        w=(m+1)*m//2

        if w<=n:
            n-=w
            tot+=1
        else:
            break

    print(tot-1)


# code by RAJ BHAVSAR
for _ in range(int(input())):
	x = int(input())
	ans = 0
	for i in range(1,40):
		temp = 2**i - 1
		summ = (temp*(temp+1))//2
		if(x >= summ):
			x -= summ
			ans += 1
	print(ans)


# code by RAJ BHAVSAR
for _ in range(int(input())):
	x = int(input())
	ans = 0
	for i in range(1,40):
		temp = 2**i - 1
		summ = (temp*(temp+1))/2
		if(x >= summ):
			x -= summ
			ans += 1
	print(ans)


li =[1]
i= 1
while i<= 10**18:
	i = i*2 +1
	li.append(i)
for _ in range(int(input())):
	x = int(input())
	cnt = 0
	for i in li:
		if i*(i+1)//2>x:
			break
		x -= i*(i+1)//2
		cnt +=1
	print(cnt)


for i in range(int(input())):
    x=int(input())
    count=0
    stair=1
    cell=1
    while((x-cell)>=0):
        x=x-stair
        count+=1
        stair=(stair*2)+1
        cell=(stair*(stair+1))//2
    print(count)


for i in range(int(input())):
    x=int(input())
    count=0
    stair=1
    cell=1
    while((x-cell)>=0):
        x=x-cell
        count+=1
        stair=(stair*2)+1
        cell=(stair*(stair+1))//2
    print(count)


T = int(input())
maxv = 10 ** 18

for t in range(T):
    x = int(input())

    i = 0
    cnt = 0
    i = 1

    while True:
        req = (1+(i))*(i)//2
        if x-req >= 0:
            x -= req
            cnt += 1
            i = i + 2**cnt
        else:
            break

    print(cnt)


T = int(input())
maxv = 10 ** 18

for t in range(T):
    x = int(input())

    i = 0
    cnt = 0
    i = 1

    while True:
        req = (1+(2**i-1))*(2**i-1)/2
        if x-req >= 0:
            x -= req
            i = i+1
            cnt += 1
        else:
            break

    print(cnt)


N=70
X=[(-1+(1<<(i+1)))*(1<<i) for i in range(N+1)]
def solve(x):
    res=0
    tmp=x
    for i in range(len(X)-1,-1,-1):
        if tmp>=X[i]:
            tmp-=X[i]
            res+=1
    return res
t=int(input())
for i in range(t):
    x=int(input())
    print(solve(x))


N=70
X=[(-1+(1<<(i+1)))*(1<<i) for i in range(N)]
def solve(x):
    res=0
    tmp=x
    for i in range(N-1,-1,-1):
        if tmp>=X[i]:
            tmp-=X[i]
            res+=1
    return res
t=int(input())
for i in range(t):
    x=int(input())
    print(solve(x))


N=70
X=[(-1+(1<<(i+1)))*(1<<i) for i in range(N)]
def solve(x):
    res=0
    tmp=x
    for i in range(N):
        if tmp>=X[i]:
            tmp-=X[i]
            res+=1
    return res
t=int(input())
for i in range(t):
    x=int(input())
    print(solve(x))


t = int(input())
c = 60
while(t>0):
    n = int(input())
    st,s = 0,0
    for i in range(1,c,2):
        s = s + (i*(i+1)//2)
        if(s<=n):
            st+=1
    print(st)
    t-=1


def myfunc(n):
    return (2**(n-1))*((2**n)-1)
for _ in range(int(input())):
    x=int(input())
    ans=1
    if x==1:
        print(ans)
    else:
        while myfunc(ans)<x:
            ans+=1
        print(ans-1)


def myfunc(n):
    return (2**(n-1))*((2**n)-1)
for _ in range(int(input())):
    x=int(input())
    ans=1
    if x==1:
        print(ans)
    else:
        cv=myfunc(ans)
        while cv<=x:
            x-=cv
            ans+=1
            cv=myfunc(ans)
        print(ans-1)


import sys
import math
import itertools
import functools
import collections
import operator
import fileinput
import copy

ORDA = 97  # a
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return [int(i) for i in input().split()]
def lcm(a, b): return abs(a * b) // math.gcd(a, b)
def revn(n): return str(n)[::-1]
def dd(): return collections.defaultdict(int)
def ddl(): return collections.defaultdict(list)
def sieve(n):
    if n < 2: return list()
    prime = [True for _ in range(n + 1)]
    p = 3
    while p * p <= n:
        if prime[p]:
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 2
    r = [2]
    for p in range(3, n + 1, 2):
        if prime[p]:
            r.append(p)
    return r
def divs(n, start=2):
    r = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if (n % i == 0):
            if (n / i == i):
                r.append(i)
            else:
                r.extend([i, n // i])
    return r
def divn(n, primes):
    divs_number = 1
    for i in primes:
        if n == 1:
            return divs_number
        t = 1
        while n % i == 0:
            t += 1
            n //= i
        divs_number *= t
def prime(n):
    if n == 2: return True
    if n % 2 == 0 or n <= 1: return False
    sqr = int(math.sqrt(n)) + 1
    for d in range(3, sqr, 2):
        if n % d == 0: return False
    return True
def convn(number, base):
    new_number = 0
    while number > 0:
        new_number += number % base
        number //= base
    return new_number
def cdiv(n, k): return n // k + (n % k != 0)
def ispal(s):
    for i in range(len(s) // 2 + 1):
        if s[i] != s[-i - 1]:
            return False
    return True

a = []
t = 1
for i in range(1, 32):
    a.append(t)
    t += t + 1

for _ in range(ii()):
    n = ii()
    ans = 0
    for i in range(31):
        n -= (a[i] * (a[i] + 1)) // 2
        ans += 1
       # print(n)
        if n <= (a[i + 1] * (a[i + 1] + 1)) // 2:
            break
    print(ans)


import sys
import math
import itertools
import functools
import collections
import operator
import fileinput
import copy

ORDA = 97  # a
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return [int(i) for i in input().split()]
def lcm(a, b): return abs(a * b) // math.gcd(a, b)
def revn(n): return str(n)[::-1]
def dd(): return collections.defaultdict(int)
def ddl(): return collections.defaultdict(list)
def sieve(n):
    if n < 2: return list()
    prime = [True for _ in range(n + 1)]
    p = 3
    while p * p <= n:
        if prime[p]:
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 2
    r = [2]
    for p in range(3, n + 1, 2):
        if prime[p]:
            r.append(p)
    return r
def divs(n, start=2):
    r = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if (n % i == 0):
            if (n / i == i):
                r.append(i)
            else:
                r.extend([i, n // i])
    return r
def divn(n, primes):
    divs_number = 1
    for i in primes:
        if n == 1:
            return divs_number
        t = 1
        while n % i == 0:
            t += 1
            n //= i
        divs_number *= t
def prime(n):
    if n == 2: return True
    if n % 2 == 0 or n <= 1: return False
    sqr = int(math.sqrt(n)) + 1
    for d in range(3, sqr, 2):
        if n % d == 0: return False
    return True
def convn(number, base):
    new_number = 0
    while number > 0:
        new_number += number % base
        number //= base
    return new_number
def cdiv(n, k): return n // k + (n % k != 0)
def ispal(s):
    for i in range(len(s) // 2 + 1):
        if s[i] != s[-i - 1]:
            return False
    return True

a = []
t = 1
for i in range(1, 32):
    a.append(t)
    t += t + 1

for _ in range(ii()):
    n = ii()
    ans = 0
    for i in range(31):
        n -= ((a[i] * (a[i] + 1)) // 2)
        ans += 1
        # print(n)
        if n < (a[i + 1] * (a[i + 1] + 1)) // 2:
            break
    print(ans)


import sys
input = sys.stdin.readline
ins = lambda: input().rstrip()
ini = lambda: int(input().rstrip())
inm = lambda: map(int, input().rstrip().split())
inl = lambda: list(map(int, input().split()))
out = lambda x, s='\n': print(s.join(map(str, x)))

output = []
t = ini()
for _ in range(t):
    n = ini()
    ans = 0
    nice = 1
    while n > 0:
        x = nice * (nice+1) // 2
        if n - x >= 0:
            n -= x
            ans += 1
            nice = nice * 2 + 1
        else:
            break
    output.append(ans)
out(output)


import sys
input = sys.stdin.readline
ins = lambda: input().rstrip()
ini = lambda: int(input().rstrip())
inm = lambda: map(int, input().rstrip().split())
inl = lambda: list(map(int, input().split()))
out = lambda x, s='\n': print(s.join(map(str, x)))

t = ini()
for _ in range(t):
    n = ini()
    ans = 0
    count = 1
    while n > 0:
        x = count * (count+1) // 2
        if n - x >= 0:
            n -= x
            ans += 1
            count = count * 2 + 1
        else:
            break
    print(ans)


from math import sqrt, log

t = int(input())

for test in range(t):
    x = int(input())
    a = log((3. + sqrt(1. + 24. * x)) / 4.) / log(2.)
    print (int(a))


from math import sqrt, log

t = int(input())

def f(n, x):
    return int((2 ** n - 1) * (2 ** (n + 1) - 1) / 3) <= x

for test in range(t):
    x = int(input())
    n = 0
    while f(n, x):
        n += 1
    print (n - 1)


from math import sqrt, log

t = int(input())

for test in range(t):
    x = int(input())
    a = log(int((3. + sqrt(1. + 24. * x)) / 4.) * 1.) / log(2.)
    print (int(a))


from math import sqrt, log

t = int(input())

for test in range(t):
    x = int(input())
    n = 1
    while x >= 0:
        x -= (2 ** n - 1) * (2 ** n) // 2
        n += 1
    print (n - 2)


t = int(input())
for _ in range(t):
    x = int(input()) - 1
    n = 1
    arr = [1]
    while True:
        n *= 2
        arr.append(n)
        s = sum(arr)*(sum(arr)+1)/2
        if x - s < 0:
            arr.remove(n)
            break
        x -= s
    print(len(arr))


#include <iostream>
#include <string>
#include <utility>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <cmath>

using namespace std;
typedef long long LL;
typedef pair<int,int> pii;
typedef map<int,vector<int>> mpivi;
#define ff first
#define ss second
#define pb push_back

class Node{
public:
	int v,l,r;

	Node(){
	 l=-1;
	 r=-1;
	}
};

class SegTree
{
	int n;
	int cur;
	vector<Node> tree;
	vector<int> a;

	void build(int lo,int hi,int id){
		int pos=(hi+lo)/2;
		if (pos>lo){
			cur++;
			tree[id].l=cur;
			build(lo,pos,tree[id].l);
			cur++;
			tree[id].r=cur;
			build(pos,hi,tree[id].r);
		}
	}

	void setValue(int idx,int val,int lo,int hi,int id){
		tree[id].v+=val-a[idx];
		if (lo+1==hi) return;
		int pos=(lo+hi)/2;
		if (idx<pos) setValue(idx,val,lo,pos,tree[id].l);
		else setValue(idx,val,pos,hi,tree[id].r);
	}

	int query(int a,int b,int lo,int hi,int id){
		if (a>b){
			return query(0,n,0,n,0)-query(b,a,0,n,0);
		}
		if (a<=lo && b>=hi) return tree[id].v;
		int res=0;
		int pos=(hi+lo)/2;
		if (a<pos){
			res+=query(a,b,lo,pos,tree[id].l);
		}
		if (b>pos){
			res+=query(a,b,pos,hi,tree[id].r);
		}
		return res;
	}

public:
	SegTree(int size){
		n=size;
		tree=vector<Node>(2*n+10);
		cur=0;
		a=vector<int>(n,0);
		build(0,n,cur);
	}
	void setValue(int idx,int val){
		setValue(idx,val,0,n,0);
	}
	int query(int a,int b){
		return query(a,b,0,n,0);
	}
	//~SegTree(void);

};

class Solution {
	int n;

	vector<int> a;
	map<int,vector<int>> mp;
	//vector<Node> tree;
	//int cid;
	/*void build(int lo,int hi,int id){
		tree[id].v=hi-lo;
		int pos=(hi+lo)/2;
		if (pos>lo){
			cid++;
			tree[id].l=cid;
			build(lo,pos,cid);
			cid++;
			tree[id].r=cid;
			build(pos,hi,cid);
		}

	}
	int query(int a,int b,int lo,int hi,int id){
		if (a>b){
			return query(0,n,0,n,0)-query(b,a,0,n,0);
		}
		if (a<=lo && b>=hi) return tree[id].v;
		int res=0;
		int pos=(hi+lo)/2;
		if (a<pos){
			res+=query(a,b,lo,pos,tree[id].l);
		}
		if (b>pos){
			res+=query(a,b,pos,hi,tree[id].r);
		}
		return res;
	}
	void del(int v,int lo ,int hi,int id){
		tree[id].v--;
		if (lo+1==hi) return;
		int pos=(lo+hi)/2;
		if (v<pos) del(v,lo,pos,tree[id].l);
		else del(v,pos,hi,tree[id].r);
	}*/
public:
	void sol(){
		cin>>n;
		a=vector<int>(n);
		SegTree tree=SegTree(n);
		for (int i=0;i<n;i++)cin>>a[i];
		mp=map<int,vector<int>>();
		for (int i=0;i<n;i++){
			int v=a[i];
			mp[v].push_back(i);
			tree.setValue(i,1);

		}

		//tree=vector<Node>(2*n+5);
		//cid=0;
		//build(0,n,0);
		int cur=0;
		LL res=0;
		for (mpivi::iterator it=mp.begin();it!=mp.end();it++){
			vector<int> v=(*it).second;
			int start=lower_bound(v.begin(),v.end(),cur)-v.begin();
			if (start>0){
				res+=tree.query(cur,v[start-1]);
				cur=(v[start-1]+1)%n;
			}else{
				res+=tree.query(cur,v.back());
				cur=(v.back()+1)%n;
			}
			res+=1;

			for (int i=0;i<v.size();i++) tree.setValue(v[i],0);
		}
		cout<<res;

	}

};

int main(int argc, char *argv[])
{
	ios_base::sync_with_stdio(0);
	cin.tie(NULL);
	cout.tie(NULL);
	Solution s;
	s.sol();
	//int a;cin>>a;
	return 0;
}


#include <iostream>
#include <string>
#include <utility>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <cmath>

using namespace std;
typedef long long LL;
typedef pair<int,int> pii;
typedef map<int,vector<int>> mpivi;
#define ff first
#define ss second
#define pb push_back

class Node{
public:
	int v,l,r;

	Node(){
		v=0;
	 l=-1;
	 r=-1;
	}
};

class SegTree
{
	int n;
	int cur;
	vector<Node> tree;
	vector<int> a;

	void build(int lo,int hi,int id){
		int pos=(hi+lo)/2;
		if (pos>lo){
			cur++;
			tree[id].l=cur;
			build(lo,pos,tree[id].l);
			cur++;
			tree[id].r=cur;
			build(pos,hi,tree[id].r);
		}
	}

	void setValue(int idx,int val,int lo,int hi,int id){
		tree[id].v+=val-a[idx];
		if (lo+1==hi) return;
		int pos=(lo+hi)/2;
		if (idx<pos) setValue(idx,val,lo,pos,tree[id].l);
		else setValue(idx,val,pos,hi,tree[id].r);
	}

	int query(int a,int b,int lo,int hi,int id){
		if (a>b){
			return query(0,n,0,n,0)-query(b,a,0,n,0);
		}
		if (a<=lo && b>=hi) return tree[id].v;
		int res=0;
		int pos=(hi+lo)/2;
		if (a<pos){
			res+=query(a,b,lo,pos,tree[id].l);
		}
		if (b>pos){
			res+=query(a,b,pos,hi,tree[id].r);
		}
		return res;
	}

public:
	SegTree(int size){
		n=size;
		tree=vector<Node>(2*n+10);
		cur=0;
		a=vector<int>(n,0);
		build(0,n,cur);
	}
	void setValue(int idx,int val){
		setValue(idx,val,0,n,0);
	}
	int query(int a,int b){
		return query(a,b,0,n,0);
	}
	//~SegTree(void);

};

class Solution {
	int n;

	vector<int> a;
	map<int,vector<int>> mp;
	//vector<Node> tree;
	//int cid;
	/*void build(int lo,int hi,int id){
		tree[id].v=hi-lo;
		int pos=(hi+lo)/2;
		if (pos>lo){
			cid++;
			tree[id].l=cid;
			build(lo,pos,cid);
			cid++;
			tree[id].r=cid;
			build(pos,hi,cid);
		}

	}
	int query(int a,int b,int lo,int hi,int id){
		if (a>b){
			return query(0,n,0,n,0)-query(b,a,0,n,0);
		}
		if (a<=lo && b>=hi) return tree[id].v;
		int res=0;
		int pos=(hi+lo)/2;
		if (a<pos){
			res+=query(a,b,lo,pos,tree[id].l);
		}
		if (b>pos){
			res+=query(a,b,pos,hi,tree[id].r);
		}
		return res;
	}
	void del(int v,int lo ,int hi,int id){
		tree[id].v--;
		if (lo+1==hi) return;
		int pos=(lo+hi)/2;
		if (v<pos) del(v,lo,pos,tree[id].l);
		else del(v,pos,hi,tree[id].r);
	}*/
public:
	void sol(){
		cin>>n;
		a=vector<int>(n);
		SegTree tree=SegTree(n);
		for (int i=0;i<n;i++)cin>>a[i];
		mp=map<int,vector<int>>();
		for (int i=0;i<n;i++){
			int v=a[i];
			mp[v].push_back(i);
			tree.setValue(i,1);

		}

		//tree=vector<Node>(2*n+5);
		//cid=0;
		//build(0,n,0);
		int cur=0;
		LL res=0;
		for (mpivi::iterator it=mp.begin();it!=mp.end();it++){
			vector<int> v=(*it).second;
			int start=lower_bound(v.begin(),v.end(),cur)-v.begin();
			if (start>0){
				res+=tree.query(cur,v[start-1]);
				cur=(v[start-1]+1)%n;
			}else{
				res+=tree.query(cur,v.back());
				cur=(v.back()+1)%n;
			}
			res+=1;

			for (int i=0;i<v.size();i++) tree.setValue(v[i],0);
		}
		cout<<res;

	}

};

int main(int argc, char *argv[])
{
	ios_base::sync_with_stdio(0);
	cin.tie(NULL);
	cout.tie(NULL);
	Solution s;
	s.sol();
	//int a;cin>>a;
	return 0;
}


#include <iostream>
#include <string>
#include <utility>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <cmath>

using namespace std;
typedef long long LL;
typedef pair<int,int> pii;
typedef map<int,vector<int>> mpivi;
#define ff first
#define ss second
#define pb push_back

class Node{
public:
	int v,l,r;

	Node(){
		v=0;
	 l=-1;
	 r=-1;
	}
};

class SegTree
{
	int n;
	int cur;
	vector<Node> tree;
	vector<int> a;

	void build(int lo,int hi,int id){
		int pos=(hi+lo)/2;
		if (pos>lo){
			cur++;
			tree[id].l=cur;
			build(lo,pos,tree[id].l);
			cur++;
			tree[id].r=cur;
			build(pos,hi,tree[id].r);
		}
	}

	void setValue(int idx,int val,int lo,int hi,int id){
		tree[id].v+=val-a[idx];
		if (lo+1==hi) return;
		int pos=(lo+hi)/2;
		if (idx<pos) setValue(idx,val,lo,pos,tree[id].l);
		else setValue(idx,val,pos,hi,tree[id].r);
	}

	int query(int a,int b,int lo,int hi,int id){
		if (a>b){
			return query(0,n,0,n,0)-query(b,a,0,n,0);
		}
		if (a<=lo && b>=hi) return tree[id].v;
		int res=0;
		int pos=(hi+lo)/2;
		if (a<pos){
			res+=query(a,b,lo,pos,tree[id].l);
		}
		if (b>pos){
			res+=query(a,b,pos,hi,tree[id].r);
		}
		return res;
	}

public:
	SegTree(int size){
		n=size;
		tree=vector<Node>(2*n+10);
		cur=0;
		a=vector<int>(n,0);
		build(0,n,cur);
	}
	void setValue(int idx,int val){
		setValue(idx,val,0,n,0);
		a[idx]=val;
	}
	int query(int a,int b){
		return query(a,b,0,n,0);
	}
	//~SegTree(void);

};

class Solution {
	int n;

	vector<int> a;
	map<int,vector<int>> mp;
	//vector<Node> tree;
	//int cid;
	/*void build(int lo,int hi,int id){
		tree[id].v=hi-lo;
		int pos=(hi+lo)/2;
		if (pos>lo){
			cid++;
			tree[id].l=cid;
			build(lo,pos,cid);
			cid++;
			tree[id].r=cid;
			build(pos,hi,cid);
		}

	}
	int query(int a,int b,int lo,int hi,int id){
		if (a>b){
			return query(0,n,0,n,0)-query(b,a,0,n,0);
		}
		if (a<=lo && b>=hi) return tree[id].v;
		int res=0;
		int pos=(hi+lo)/2;
		if (a<pos){
			res+=query(a,b,lo,pos,tree[id].l);
		}
		if (b>pos){
			res+=query(a,b,pos,hi,tree[id].r);
		}
		return res;
	}
	void del(int v,int lo ,int hi,int id){
		tree[id].v--;
		if (lo+1==hi) return;
		int pos=(lo+hi)/2;
		if (v<pos) del(v,lo,pos,tree[id].l);
		else del(v,pos,hi,tree[id].r);
	}*/
public:
	void sol(){
		cin>>n;
		a=vector<int>(n);
		SegTree tree=SegTree(n);
		for (int i=0;i<n;i++)cin>>a[i];
		mp=map<int,vector<int>>();
		for (int i=0;i<n;i++){
			int v=a[i];
			mp[v].push_back(i);
			tree.setValue(i,1);

		}

		//tree=vector<Node>(2*n+5);
		//cid=0;
		//build(0,n,0);
		int cur=0;
		LL res=0;
		for (mpivi::iterator it=mp.begin();it!=mp.end();it++){
			vector<int> v=(*it).second;
			int start=lower_bound(v.begin(),v.end(),cur)-v.begin();
			if (start>0){
				res+=tree.query(cur,v[start-1]);
				cur=(v[start-1]+1)%n;
			}else{
				res+=tree.query(cur,v.back());
				cur=(v.back()+1)%n;
			}
			res+=1;

			for (int i=0;i<v.size();i++) tree.setValue(v[i],0);
		}
		cout<<res;

	}

};

int main(int argc, char *argv[])
{
	ios_base::sync_with_stdio(0);
	cin.tie(NULL);
	cout.tie(NULL);
	Solution s;
	s.sol();
	//int a;cin>>a;
	return 0;
}


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

int main(){

	int n;
	cin>>n;
	int arr[n+1];
	vector<int> v[100010];
	for(int i = 0; i < n; i++){
		cin>>arr[i];
		v[arr[i]].push_back(i);
	}
	sort(arr,arr+n);
	arr[n] = arr[n-1] + 1;
	int pointer = -1;       //ans+1
	int index = 0;
	vector<pair<int,int> > loop;
	vector<int>::iterator f;
	int i = arr[index];
	while(i <= arr[n-1]){
		f = lower_bound(v[i].begin(),v[i].end(),pointer);
		int curr = f - v[i].begin();
		//cout<<curr<<endl;
		if(curr==0){
			loop.push_back(make_pair(0,v[i].size() ));
			pointer = v[i].back();
		}
		else{
			loop.push_back(make_pair(1,v[i].size() ));
			pointer = curr;
		}
		int prev = i;
		while(prev==i){
			i = arr[++index];
		}
	}
	int ans = n, curr_size = 0;
	for(int i = 0; i < loop.size(); i++){
		//cout<<loop[i].first<<" "<<loop[i].second<<endl;
		if(loop[i].first==0){
			curr_size += loop[i].second;
		}
		else{
			n = n - curr_size;
			curr_size = loop[i].second;
			ans += n;
		}
	}
	cout<<ans<<endl;

	return 0;
}


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

int main(){

	int n;
	cin>>n;
	int arr[n+1];
	vector<int> v[100010];
	for(int i = 0; i < n; i++){
		cin>>arr[i];
		v[arr[i]].push_back(i);
	}
	sort(arr,arr+n);
	arr[n] = arr[n-1] + 1;
	int pointer = -1;       //ans+1
	int index = 0;
	vector<pair<int,int> > loop;
	vector<int>::iterator f;
	int i = arr[index];
	while(i <= arr[n-1]){
		f = lower_bound(v[i].begin(),v[i].end(),pointer);
		int curr = f - v[i].begin();
		//cout<<curr<<v[i][0]<<endl;
		if(pointer<v[i][0]){
			loop.push_back(make_pair(0,v[i].size() ));
			pointer = v[i].back();
		}
		else{
			loop.push_back(make_pair(1,v[i].size() ));
			pointer = curr-1;

		}
		int prev = i;
		while(prev==i){
			i = arr[++index];
		}
	}
	int ans = n, curr_size = 0;
	for(int i = 0; i < loop.size(); i++){
		//cout<<loop[i].first<<" "<<loop[i].second<<endl;
		if(loop[i].first==0){
			curr_size += loop[i].second;
		}
		else{
			n = n - curr_size;
			curr_size = loop[i].second;
			ans += n;
		}
	}
	cout<<ans<<endl;

	return 0;
}


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

int main(){

	int n;
	cin>>n;
	int arr[n+1];
	vector<int> v[100010];
	for(int i = 0; i < n; i++){
		cin>>arr[i];
		v[arr[i]].push_back(i);
	}
	sort(arr,arr+n);
	arr[n] = arr[n-1] + 1;
	int pointer = -1;       //ans+1
	int index = 0;
	vector<pair<int,int> > loop;
	vector<int>::iterator f;
	int i = arr[index];
	while(i <= arr[n-1]){
		f = lower_bound(v[i].begin(),v[i].end(),pointer);
		int curr = f - v[i].begin();
		//cout<<curr<<v[i][0]<<endl;
		if(pointer<v[i][0]){
			loop.push_back(make_pair(0,v[i].size() ));
			pointer = v[i].back();
		}
		else{
			loop.push_back(make_pair(1,v[i].size() ));
			pointer = v[i][curr-1];

		}
		int prev = i;
		while(prev==i){
			i = arr[++index];
		}
	}
	int ans = n, curr_size = 0;
	for(int i = 0; i < loop.size(); i++){
		//cout<<loop[i].first<<" "<<loop[i].second<<endl;
		if(loop[i].first==0){
			curr_size += loop[i].second;
		}
		else{
			n = n - curr_size;
			curr_size = loop[i].second;
			ans += n;
		}
	}
	cout<<ans<<endl;

	return 0;
}


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

int main(){

	int n;
	cin>>n;
	int arr[n+1];
	vector<int> v[100010];
	for(int i = 0; i < n; i++){
		cin>>arr[i];
		v[arr[i]].push_back(i);
	}
	sort(arr,arr+n);
	arr[n] = arr[n-1] + 1;
	int pointer = -1;
	int index = 0;
	vector<pair<int,int> > loop;
	vector<int>::iterator f;
	//int i = arr[index];
	for(int i = 0; i <=100001; i++){
		//cout<<i<<endl;
		if(v[i].size()==0) continue;
		f = lower_bound(v[i].begin(),v[i].end(),pointer);
		int curr = f - v[i].begin();
		//cout<<curr<<v[i][0]<<endl;
		if(curr==0){
			loop.push_back(make_pair(0,v[i].size() ));
			pointer = v[i].back();
		}
		else{
			loop.push_back(make_pair(0,v[i].size()-curr));
			loop.push_back(make_pair(1,curr));
			pointer = v[i][curr-1];

		}
		/*int prev = i;
		while(prev==i){
			i = arr[++index];
		}*/
	}
	long long ans = n, curr_size = 0;
	for(int i = 0; i < loop.size(); i++){
		//cout<<loop[i].first<<" "<<loop[i].second<<endl;
		if(loop[i].first==0){
			curr_size += loop[i].second;
		}
		else{
			n = n - curr_size;
			curr_size = loop[i].second;
			ans += n;
		}
	}
	cout<<ans<<endl;

	return 0;
}


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

int main(){

	int n;
	cin>>n;
	int arr[n+1];
	vector<int> v[100010];
	for(int i = 0; i < n; i++){
		cin>>arr[i];
		v[arr[i]].push_back(i);
	}
	sort(arr,arr+n);
	arr[n] = arr[n-1] + 1;
	int pointer = -1;
	int index = 0;
	vector<pair<int,int> > loop;
	vector<int>::iterator f;
	//int i = arr[index];
	for(int i = 0; i <=100001; i++){
		//cout<<i<<endl;
		if(v[i].size()==0) continue;
		f = lower_bound(v[i].begin(),v[i].end(),pointer);
		int curr = f - v[i].begin();
		//cout<<curr<<v[i][0]<<endl;
		if(curr==0){
			loop.push_back(make_pair(0,v[i].size() ));
			pointer = v[i].back();
		}
		else{
			loop.push_back(make_pair(0,v[i].size()-curr));
			loop.push_back(make_pair(1,curr));
			pointer = v[i][curr-1];

		}
		/*int prev = i;
		while(prev==i){
			i = arr[++index];
		}*/
	}
	int ans = n, curr_size = 0;
	for(int i = 0; i < loop.size(); i++){
		//cout<<loop[i].first<<" "<<loop[i].second<<endl;
		if(loop[i].first==0){
			curr_size += loop[i].second;
		}
		else{
			n = n - curr_size;
			curr_size = loop[i].second;
			ans += n;
		}
	}
	cout<<ans<<endl;

	return 0;
}


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

int main(){

	int n;
	cin>>n;
	int arr[n+1];
	vector<int> v[100010];
	for(int i = 0; i < n; i++){
		cin>>arr[i];
		v[arr[i]].push_back(i);
	}
	sort(arr,arr+n);
	arr[n] = arr[n-1] + 1;
	int pointer = -1;       //ans+1
	int index = 0;
	vector<pair<int,int> > loop;
	vector<int>::iterator f;
	int i = arr[index];
	while(i <= arr[n-1]){
		f = lower_bound(v[i].begin(),v[i].end(),pointer);
		int curr = f - v[i].begin();
		//cout<<curr<<v[i][0]<<endl;
		if(pointer<v[i][0]){
			loop.push_back(make_pair(0,v[i].size() ));
			pointer = v[i].back();
		}
		else{
			loop.push_back(make_pair(1,v[i].size() ));
			pointer = arr[curr-1];

		}
		int prev = i;
		while(prev==i){
			i = arr[++index];
		}
	}
	int ans = n, curr_size = 0;
	for(int i = 0; i < loop.size(); i++){
		//cout<<loop[i].first<<" "<<loop[i].second<<endl;
		if(loop[i].first==0){
			curr_size += loop[i].second;
		}
		else{
			n = n - curr_size;
			curr_size = loop[i].second;
			ans += n;
		}
	}
	cout<<ans<<endl;

	return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(lli i=(lli)a;i<=(lli)b;i++)
#define endl "\n"
#define mp make_pair
#define X first
#define Y second
#define inf 1e18
#define mod 1000000007
#define pb push_back
#define pi 3.14159265359
#define gc getchar
#define Case cout<<"Case #"<<++cas<<": ";
#define fastio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define all(v) v.begin(),v.end()
// #define lli int
typedef long long int lli;
typedef pair<int,int> pii;
typedef pair<lli,int> pli;
typedef vector<pii> vii;
typedef pair<lli,lli> pll;
typedef vector<lli> vl;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<vl> vvl;

#define pr(...) dbs(#__VA_ARGS__, __VA_ARGS__)
template <class T> void dbs(string str, T t) {cerr << str << " : " << t << "\n";}
template <class T, class... S> void dbs(string str, T t, S... s) {int idx = str.find(','); cerr << str.substr(0, idx) << " : " << t << ","; dbs(str.substr(idx + 1), s...);}
template <class S, class T>ostream& operator <<(ostream& os, const pair<S, T>& p) {return os << "(" << p.first << ", " << p.second << ")";}
template <class T>ostream& operator <<(ostream& os, const vector<T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class T>ostream& operator <<(ostream& os, const set<T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class S, class T>ostream& operator <<(ostream& os, const map<S, T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class T> void prc(T a, T b) {cerr << "["; for (T i = a; i != b; ++i) {if (i != a) cerr << ", "; cerr << *i;} cerr << "]\n";}

bool mark[100009];

struct FenwickTree{
lli v[200009];
void update(lli n)
{
	for(lli i=n;i<=200000;i=i+(i&(-i)))
		v[i]++;
}

lli query(lli n)
{
	lli ret=0;
	for(lli i=n;i>=1;i=i-(i&(-i)))
		ret+=v[i];
	return ret;
}
} T;

int main()
{
	fastio;
	lli n,ans=0;
	cin>>n;
	vl A(n+1),B(n+1);
	FOR(i,1,n)
	cin>>A[i];
	B[n]=0;
	// FenwickTree T;
	if(!mark[A[n]])
		T.update(A[n]);
	mark[A[n]]=1;
	for(lli i=n-1;i>=1;i--)
	{
		B[i]=T.query(A[i]-1);
		T.update(A[i]);
		if(!mark[A[i]])
		mark[A[i]]=1;
	}
	for(lli i=n-1;i>=1;i--)
		{if(A[i+1]<A[i])
			B[i]=min(B[i+1]+1,B[i]);
		else B[i]=min(B[i],B[i+1]);}
	// pr(B);
	FOR(i,1,n)
		ans+=B[i];
	ans+=n;
	cout<<ans;
}


#include<bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(lli i=(lli)a;i<=(lli)b;i++)
#define endl "\n"
#define mp make_pair
#define X first
#define Y second
#define inf 1e18
#define mod 1000000007
#define pb push_back
#define pi 3.14159265359
#define gc getchar
#define Case cout<<"Case #"<<++cas<<": ";
#define fastio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define all(v) v.begin(),v.end()
// #define lli int
typedef long long int lli;
typedef pair<int,int> pii;
typedef pair<lli,int> pli;
typedef vector<pii> vii;
typedef pair<lli,lli> pll;
typedef vector<lli> vl;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<vl> vvl;

#define pr(...) dbs(#__VA_ARGS__, __VA_ARGS__)
template <class T> void dbs(string str, T t) {cerr << str << " : " << t << "\n";}
template <class T, class... S> void dbs(string str, T t, S... s) {int idx = str.find(','); cerr << str.substr(0, idx) << " : " << t << ","; dbs(str.substr(idx + 1), s...);}
template <class S, class T>ostream& operator <<(ostream& os, const pair<S, T>& p) {return os << "(" << p.first << ", " << p.second << ")";}
template <class T>ostream& operator <<(ostream& os, const vector<T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class T>ostream& operator <<(ostream& os, const set<T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class S, class T>ostream& operator <<(ostream& os, const map<S, T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class T> void prc(T a, T b) {cerr << "["; for (T i = a; i != b; ++i) {if (i != a) cerr << ", "; cerr << *i;} cerr << "]\n";}

vl v[100009];
lli T[400009];

void update(lli ind,lli a,lli b,lli x,lli y)
{
	if(a>b || x>b || x<a)
		return;
	T[ind]=max(T[ind],y);
	if(a==b) return;
	lli mid=(a+b)/2;
	update(ind<<1,a,mid,x,y);
	update(ind*2+1,mid+1,b,x,y);
}

lli query(lli ind,lli a,lli b,lli l,lli r)
{
	if(a>b || l>b || r<a || l>r)
		return 0;
	if(l<=a && r>=b)
		return T[ind];
	lli mid=(a+b)/2;
	return max(query(ind<<1,a,mid,l,r),query(ind*2+1,mid+1,b,l,r));
}

int main()
{
	lli n,a,ans=0,ind;vl w;set<lli> s;
	cin>>n;
	vl A(n+1);
	FOR(i,1,n)
	{cin>>A[i];v[A[i]].pb(i);s.insert(A[i]);}
	for(auto i:s)
	{
		w.clear();
		for(auto j:v[i])
		{
			a=max(query(1,1,n,1,j-1),query(1,1,n,j+1,n)+1);
			w.pb(a);
			ans+=a;
		}
		ind=0;
		for(auto j:v[i])
			update(1,1,n,j,w[ind++]);
	}
	cout<<ans;
}


#include<bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(lli i=(lli)a;i<=(lli)b;i++)
#define endl "\n"
#define mp make_pair
#define X first
#define Y second
#define inf 1e18
#define mod 1000000007
#define pb push_back
#define pi 3.14159265359
#define gc getchar
#define Case cout<<"Case #"<<++cas<<": ";
#define fastio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define all(v) v.begin(),v.end()
#define lli int
// typedef long long int lli;
typedef pair<int,int> pii;
typedef pair<lli,int> pli;
typedef vector<pii> vii;
typedef pair<lli,lli> pll;
typedef vector<lli> vl;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<vl> vvl;

#define pr(...) dbs(#__VA_ARGS__, __VA_ARGS__)
template <class T> void dbs(string str, T t) {cerr << str << " : " << t << "\n";}
template <class T, class... S> void dbs(string str, T t, S... s) {int idx = str.find(','); cerr << str.substr(0, idx) << " : " << t << ","; dbs(str.substr(idx + 1), s...);}
template <class S, class T>ostream& operator <<(ostream& os, const pair<S, T>& p) {return os << "(" << p.first << ", " << p.second << ")";}
template <class T>ostream& operator <<(ostream& os, const vector<T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class T>ostream& operator <<(ostream& os, const set<T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class S, class T>ostream& operator <<(ostream& os, const map<S, T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class T> void prc(T a, T b) {cerr << "["; for (T i = a; i != b; ++i) {if (i != a) cerr << ", "; cerr << *i;} cerr << "]\n";}

// struct FenwickTree{
// vl v(100009);
// void update(lli n)
// {
// 	for(lli i=n;i>=1;i=i-(i&(-i)))
// 		v[i]++;
// }

// lli query(lli n)
// {
// 	lli ret=0;
// 	for(lli i=n;i>=1;i=i-(i&(-i)))
// 		ret+=v[i];
// 	return ret;
// }
// };

int main()
{
	lli n,ans=0;
	cin>>n;
	vl A(n+1),B(n+1);
	FOR(i,1,n)
	cin>>A[i];
	B[n]=0;
	// if(!mark[A[n]])
	// 	T.update(A[n]);
	// for(lli i=n-1;i>=1;i--)
	// {
	// 	B[n]=T.query(A[i]-1);
	// 	T.update(A[i]);
	// }
	for(lli i=n-1;i>=1;i--)
		{if(A[i+1]<A[i])
			B[i]=B[i+1]+1;
		else B[i]=B[i+1];}
	// pr(B);
	FOR(i,1,n)
		ans+=B[i];
	ans+=n;
	cout<<ans;
}


#include<bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(lli i=(lli)a;i<=(lli)b;i++)
#define endl "\n"
#define mp make_pair
#define X first
#define Y second
#define inf 1e18
#define mod 1000000007
#define pb push_back
#define pi 3.14159265359
#define gc getchar
#define Case cout<<"Case #"<<++cas<<": ";
#define fastio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define all(v) v.begin(),v.end()
// #define lli int
typedef long long int lli;
typedef pair<int,int> pii;
typedef pair<lli,int> pli;
typedef vector<pii> vii;
typedef pair<lli,lli> pll;
typedef vector<lli> vl;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<vl> vvl;

#define pr(...) dbs(#__VA_ARGS__, __VA_ARGS__)
template <class T> void dbs(string str, T t) {cerr << str << " : " << t << "\n";}
template <class T, class... S> void dbs(string str, T t, S... s) {int idx = str.find(','); cerr << str.substr(0, idx) << " : " << t << ","; dbs(str.substr(idx + 1), s...);}
template <class S, class T>ostream& operator <<(ostream& os, const pair<S, T>& p) {return os << "(" << p.first << ", " << p.second << ")";}
template <class T>ostream& operator <<(ostream& os, const vector<T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class T>ostream& operator <<(ostream& os, const set<T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class S, class T>ostream& operator <<(ostream& os, const map<S, T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class T> void prc(T a, T b) {cerr << "["; for (T i = a; i != b; ++i) {if (i != a) cerr << ", "; cerr << *i;} cerr << "]\n";}

vl v[100009];
lli T[400009];

void update(lli ind,lli a,lli b,lli x,lli y)
{
	if(a>b || x>b || x<a)
		return;
	T[ind]=max(T[ind],y);
	if(a==b) return;
	lli mid=(a+b)/2;
	update(ind<<1,a,mid,x,y);
	update(1+ind<<1,mid+1,b,x,y);
}

lli query(lli ind,lli a,lli b,lli l,lli r)
{
	if(a>b || l>b || r<a || l>r)
		return 0;
	if(l<=a && r>=b)
		return T[ind];
	lli mid=(a+b)/2;
	return max(query(ind<<1,a,mid,l,r),query(1+ind<<1,mid+1,b,l,r));
}

int main()
{
	lli n,a,ans=0,ind;vl w;set<lli> s;
	cin>>n;
	vl A(n+1);
	FOR(i,1,n)
	{cin>>A[i];v[A[i]].pb(i);s.insert(A[i]);}
	for(auto i:s)
	{
		w.clear();
		for(auto j:v[i])
		{
			a=max(query(1,1,n,1,j-1),query(1,1,n,j+1,n)+1);
			w.pb(a);
			ans+=a;
		}
		ind=0;
		for(auto j:v[i])
			update(1,1,n,j,w[ind++]);
	}
	cout<<ans;
}


#include<bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(lli i=(lli)a;i<=(lli)b;i++)
#define endl "\n"
#define mp make_pair
#define X first
#define Y second
#define inf 1e18
#define mod 1000000007
#define pb push_back
#define pi 3.14159265359
#define gc getchar
#define Case cout<<"Case #"<<++cas<<": ";
#define fastio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define all(v) v.begin(),v.end()
// #define lli int
typedef long long int lli;
typedef pair<int,int> pii;
typedef pair<lli,int> pli;
typedef vector<pii> vii;
typedef pair<lli,lli> pll;
typedef vector<lli> vl;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<vl> vvl;

#define pr(...) dbs(#__VA_ARGS__, __VA_ARGS__)
template <class T> void dbs(string str, T t) {cerr << str << " : " << t << "\n";}
template <class T, class... S> void dbs(string str, T t, S... s) {int idx = str.find(','); cerr << str.substr(0, idx) << " : " << t << ","; dbs(str.substr(idx + 1), s...);}
template <class S, class T>ostream& operator <<(ostream& os, const pair<S, T>& p) {return os << "(" << p.first << ", " << p.second << ")";}
template <class T>ostream& operator <<(ostream& os, const vector<T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class T>ostream& operator <<(ostream& os, const set<T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class S, class T>ostream& operator <<(ostream& os, const map<S, T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class T> void prc(T a, T b) {cerr << "["; for (T i = a; i != b; ++i) {if (i != a) cerr << ", "; cerr << *i;} cerr << "]\n";}

bool mark[100009];

struct FenwickTree{
lli v[200009];
void update(lli n)
{
	for(lli i=n;i<=200000;i=i+(i&(-i)))
		v[i]++;
}

lli query(lli n)
{
	lli ret=0;
	for(lli i=n;i>=1;i=i-(i&(-i)))
		ret+=v[i];
	return ret;
}
} T;

int main()
{
	lli n,ans=0;
	cin>>n;
	vl A(n+1),B(n+1);
	FOR(i,1,n)
	cin>>A[i];
	B[n]=0;
	// FenwickTree T;
	if(!mark[A[n]])
		T.update(A[n]);
	for(lli i=n-1;i>=1;i--)
	{
		B[n]=T.query(A[i]-1);
		T.update(A[i]);
	}
	for(lli i=n-1;i>=1;i--)
		{if(A[i+1]<A[i])
			B[i]=min(B[i+1]+1,B[i]);
		else B[i]=min(B[i],B[i+1]);}
	// pr(B);
	FOR(i,1,n)
		ans+=B[i];
	ans+=n;
	cout<<ans;
}


#include<bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(lli i=(lli)a;i<=(lli)b;i++)
#define endl "\n"
#define mp make_pair
#define X first
#define Y second
#define inf 1e18
#define mod 1000000007
#define pb push_back
#define pi 3.14159265359
#define gc getchar
#define Case cout<<"Case #"<<++cas<<": ";
#define fastio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define all(v) v.begin(),v.end()
// #define lli int
typedef long long int lli;
typedef pair<int,int> pii;
typedef pair<lli,int> pli;
typedef vector<pii> vii;
typedef pair<lli,lli> pll;
typedef vector<lli> vl;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<vl> vvl;

#define pr(...) dbs(#__VA_ARGS__, __VA_ARGS__)
template <class T> void dbs(string str, T t) {cerr << str << " : " << t << "\n";}
template <class T, class... S> void dbs(string str, T t, S... s) {int idx = str.find(','); cerr << str.substr(0, idx) << " : " << t << ","; dbs(str.substr(idx + 1), s...);}
template <class S, class T>ostream& operator <<(ostream& os, const pair<S, T>& p) {return os << "(" << p.first << ", " << p.second << ")";}
template <class T>ostream& operator <<(ostream& os, const vector<T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class T>ostream& operator <<(ostream& os, const set<T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class S, class T>ostream& operator <<(ostream& os, const map<S, T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class T> void prc(T a, T b) {cerr << "["; for (T i = a; i != b; ++i) {if (i != a) cerr << ", "; cerr << *i;} cerr << "]\n";}
vl v[100009];
int main()
{
	lli n,ans=0,a,b,ind,upd,prev;bool flag;set<lli> s;
	cin>>n;
	vl A(n+1);
	FOR(i,1,n)
	{cin>>A[i];v[A[i]].pb(i);s.insert(A[i]);}
	ans+=v[*s.begin()].size();
	ind=1;
	flag=1;
	prev=*s.begin();
	for(auto i:s)
	{
		// pr(ans);
		upd=0;
		if(flag)
		{
			flag=!flag;
			continue;
		}
		a=v[prev].back();
		for(auto j:v[i])
			if(j<a)
			{
				b=ind+1;
				ans+=b;
				upd=max(upd,b);
			}
			else
			{
				b=ind;
				ans+=b;
				upd=max(upd,b);
			}
		ind=upd;
		prev=i;
	}
	cout<<ans;
}


#include<bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(lli i=(lli)a;i<=(lli)b;i++)
#define endl "\n"
#define mp make_pair
#define X first
#define Y second
#define inf 1e18
#define mod 1000000007
#define pb push_back
#define pi 3.14159265359
#define gc getchar
#define Case cout<<"Case #"<<++cas<<": ";
#define fastio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define all(v) v.begin(),v.end()
// #define lli int
typedef long long int lli;
typedef pair<int,int> pii;
typedef pair<lli,int> pli;
typedef vector<pii> vii;
typedef pair<lli,lli> pll;
typedef vector<lli> vl;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<vl> vvl;

#define pr(...) dbs(#__VA_ARGS__, __VA_ARGS__)
template <class T> void dbs(string str, T t) {cerr << str << " : " << t << "\n";}
template <class T, class... S> void dbs(string str, T t, S... s) {int idx = str.find(','); cerr << str.substr(0, idx) << " : " << t << ","; dbs(str.substr(idx + 1), s...);}
template <class S, class T>ostream& operator <<(ostream& os, const pair<S, T>& p) {return os << "(" << p.first << ", " << p.second << ")";}
template <class T>ostream& operator <<(ostream& os, const vector<T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class T>ostream& operator <<(ostream& os, const set<T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class S, class T>ostream& operator <<(ostream& os, const map<S, T>& p) {os << "[ "; for (auto& it : p) os << it << " "; return os << "]";}
template <class T> void prc(T a, T b) {cerr << "["; for (T i = a; i != b; ++i) {if (i != a) cerr << ", "; cerr << *i;} cerr << "]\n";}

bool mark[100009];

struct FenwickTree{
lli v[200009];
void update(lli n)
{
	for(lli i=n;i<=200000;i=i+(i&(-i)))
		v[i]++;
}

lli query(lli n)
{
	lli ret=0;
	for(lli i=n;i>=1;i=i-(i&(-i)))
		ret+=v[i];
	return ret;
}
} T;

int main()
{
	fastio;
	lli n,ans=0;
	cin>>n;
	vl A(n+1),B(n+1);
	FOR(i,1,n)
	cin>>A[i];
	B[n]=0;
	// FenwickTree T;
	if(!mark[A[n]])
		T.update(A[n]);
	mark[A[n]]=1;
	for(lli i=n-1;i>=1;i--)
	{
		B[i]=T.query(A[i]-1);
		if(!mark[A[i]])
		T.update(A[i]);
		mark[A[i]]=1;
	}
	for(lli i=n-1;i>=1;i--)
		{if(A[i+1]<A[i])
			B[i]=min(B[i+1]+1,B[i]);
		else B[i]=min(B[i],B[i+1]);}
	// pr(B);
	FOR(i,1,n)
		ans+=B[i];
	ans+=n;
	cout<<ans;
}


#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
LL n;

struct Num {
    LL x, id;
} a[1000000+10];

bool cmp(Num n1, Num n2) {
    if(n1.x == n2.x) {
        return n1.id < n2.id;
    }
    return n1.x < n2.x;
}

int main() {
    scanf("%lld", &n);

    for(int i=1;i<=n;i++) {
        scanf("%lld", &a[i].x);
        a[i].id = i;
    }

    sort(a+1, a+1+n, cmp);

    LL cnt = n, ans = 0, pos = 1;
    while(pos <= n) {
        LL tmp = 1;

        while((pos + 1 <= n) && (a[pos+1].id > a[pos].id)) {
            pos ++;
            tmp ++;
        }

        if(cnt > 0)
            ans += cnt;

        cnt -= tmp;
        //cout << cnt << endl;
        pos ++;
    }
    cout << ans << endl;
}


#include <iostream>
#include <set>
using namespace std;
typedef long long LL;

set<int> st[100000+10];
int n, a[100000+10];
int main() {
    scanf("%d", &n);
    for(int i=1;i<=n;i++) {
        scanf("%d", &a[i]);
        st[a[i]].insert(i);
    }
    LL ans = 0, cnt = n;
    for(int i=1;i<=100000;) {
        int last = 1, tmp = 0;
        if(st[i].size()) {
            last= *st[i].rbegin();
            tmp += st[i].size(); st[i].clear();
            for(int j=i+1;j<=100000;j++) {
                if(st[j].size()) {
                    int pos = *st[j].rbegin();
                    while(st[j].size() && *st[j].rbegin() > last) {
                        st[j].erase(*st[j].rbegin());
                        tmp ++;
                    }
                    last = pos;
                    if(st[j].size()) {
                        i = j;
                        break;
                    }
                }
            }
            //cout << cnt << endl;
            ans += cnt;
            cnt -= tmp;
        } else {
            i ++;
        }
    }
    cout << ans << endl;
}


#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
int n;
struct Num {
    LL x, id;
} a[100000+10];

bool cmp(Num n1, Num n2) {
    if(n1.x == n2.x) {
        return n1.id < n2.id;
    }
    return n1.x < n2.x;
}
int main() {
    scanf("%d", &n);
    for(int i=1;i<=n;i++) {
        scanf("%lld", &a[i].x);
        a[i].id = i;
    }

    sort(a+1, a+1+n, cmp);

    a[n+1].id = 1e9, a[n+1].x = 0;
    a[n+2].id = 0,   a[n+2].x = 0;

    LL cnt = n, ans = 0;
    for(int i=1;i<=n;) {
        int pos = i;
        LL tmp = 1;
        while((pos + 1 <= n) && a[pos+1].id > a[pos].id) {
            pos ++;
            tmp ++;
        }
        ans += cnt;
        cnt -= tmp;
        i = pos + 1;
    }
    cout << ans << endl;
}


#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
LL n;

struct Num {
    LL x, id;
} a[1000000+10];

bool cmp(Num n1, Num n2) {
    if(n1.x == n2.x) {
        return n1.id < n2.id;
    }
    return n1.x < n2.x;
}

int main() {
    scanf("%lld", &n);

    for(int i=1;i<=n;i++) {
        scanf("%lld", &a[i].x);
        a[i].id = i;
    }

    sort(a+1, a+1+n, cmp);

    LL cnt = n, ans = 0;
    for(LL i=1;i<=n;) {
        LL pos = i;
        LL tmp = 1;
        while((pos + 1 <= n) && a[pos+1].id > a[pos].id) {
            pos ++;
            tmp ++;
        }
        if(cnt > 0)
            ans += cnt;

        cnt -= tmp;
        //cout << cnt << endl;
        i = pos + 1;
    }
    cout << ans << endl;
}


#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
int n;
struct Num {
    LL x, id;
} a[100000+10];

bool cmp(Num n1, Num n2) {
    if(n1.x == n2.x) {
        return n1.id < n2.id;
    }
    return n1.x < n2.x;
}
int main() {
    scanf("%d", &n);
    for(int i=1;i<=n;i++) {
        scanf("%lld", &a[i].x);
        a[i].id = i;
    }

    sort(a+1, a+1+n, cmp);

    a[n+1].id = 1e9, a[n+1].x = 0;
    a[n+2].id = 0,   a[n+2].x = 0;

    LL cnt = n, ans = 0;
    for(int i=1;i<=n;) {
        int pos = i;
        LL tmp = 1;
        while(a[pos+1].id > a[pos].id) {
            pos ++;
            if(pos + 1 <= n) {
                tmp ++;
            }
        }
        if(cnt > 0) ans += cnt;
        cnt -= tmp;
        i = pos + 1;
    }
    cout << ans << endl;
}


#pragma comment(linker, "/STACK:64000000")
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <ctime>
#include <sstream>
#include <algorithm>
#include <functional>
#include <numeric>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>

using namespace std;

#define f first
#define s second
#define pb push_back
#define mp make_pair
#define ll long long
#define pii pair < int, int >
#define pll pair < long long, long long>
#define ull unsigned long long
#define y1 stupid_cmath
#define left stupid_left
#define right stupid_right
#define vi vector <int>
#define sz(a) (int)a.size()
#define forit(it, s) for(__typeof(s.begin()) it = s.begin(); it != s.end(); it++)
#define all(a) a.begin(), a.end()
#define sqr(x) ((x) * (x))

const int inf = (int)1e9;
const int mod = inf + 7;
const double eps = 1e-9;
const double pi = acos(-1.0);

int n, a[100100];
set<int> s[100100];
int b[100100];
int t[4 * 100100];
int pos = 0;

void build(int v, int tl, int tr) {
    if (tl == tr) t[v] = 1;
    else {
        int mid = (tl + tr) >> 1;
        build(2 * v, tl, mid);
        build(2 * v + 1, mid + 1, tr);
        t[v] = t[2 * v] + t[2 * v + 1];
    }
}

int get(int v, int tl, int tr, int l, int r) {
    if (l > tr || r < tl) return 0;
    if (l <= tl && tr <= r) return t[v];
    int mid = (tl + tr) >> 1;
    int ans1 = get(2 * v, tl, mid, l, r);
    int ans2 = get(2 * v + 1, mid + 1, tr, l, r);
    return ans1 + ans2;
}

void update(int v, int tl, int tr, int pos, int val) {
    if (tl == tr) t[v] = val;
    else {
        int mid = (tl + tr) >> 1;
        if (pos <= mid) update(2 * v, tl, mid, pos, val);
        else update(2 * v + 1, mid + 1, tr, pos, val);
        t[v] = t[2 * v] + t[2 * v + 1];
    }
}

int calc(int l, int r) {
    if (l <= r) return get(1, 0, n - 1, l, r);
    else return get(1, 0, n - 1, l, n - 1) + get(1, 0, n - 1, 0, r);
}

int nxt(int x, int j) {
    __typeof(s[x].begin()) it = s[x].lower_bound(j);
    if (it == s[x].end()) it = s[x].begin();
    return *it;
}

int main(){

    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d", a + i);
        b[i] = a[i];
        s[a[i]].insert(i);
    }

    sort(b, b + n);

    build(1, 0, n - 1);

    int cur = 0;
    ll ans = 0;

    for (int it = 0; it < n; it++) {
        int x = b[it];
        int j = nxt(x, cur);
        ans += calc(cur, j);
        update(1, 0, n - 1, j, 0);
        s[x].erase(j);
        cur = j;
    }

    cout << ans << endl;

    return 0;
}


#pragma comment(linker, "/STACK:64000000")
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <ctime>
#include <sstream>
#include <algorithm>
#include <functional>
#include <numeric>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>

using namespace std;

#define f first
#define s second
#define pb push_back
#define mp make_pair
#define ll long long
#define pii pair < int, int >
#define pll pair < long long, long long>
#define ull unsigned long long
#define y1 stupid_cmath
#define left stupid_left
#define right stupid_right
#define vi vector <int>
#define sz(a) (int)a.size()
#define forit(it, s) for(__typeof(s.begin()) it = s.begin(); it != s.end(); it++)
#define all(a) a.begin(), a.end()
#define sqr(x) ((x) * (x))

const int inf = (int)1e9;
const int mod = inf + 7;
const double eps = 1e-9;
const double pi = acos(-1.0);

int n, a[100100];
set<int> s[100100];
int b[100100];
int t[4 * 100100];
int pos = 0;

void build(int v, int tl, int tr) {
    if (tl == tr) t[v] = 1;
    else {
        int mid = (tl + tr) >> 1;
        build(2 * v, tl, mid);
        build(2 * v + 1, mid + 1, tr);
        t[v] = t[2 * v] + t[2 * v + 1];
    }
}

int get(int v, int tl, int tr, int l, int r) {
    if (l > tr || r < tl) return 0;
    if (l <= tl && tr <= r) return t[v];
    int mid = (tl + tr) >> 1;
    int ans1 = get(2 * v, tl, mid, l, r);
    int ans2 = get(2 * v + 1, mid + 1, tr, l, r);
    return ans1 + ans2;
}

void update(int v, int tl, int tr, int pos, int val) {
    if (tl == tr) t[v] = val;
    else {
        int mid = (tl + tr) >> 1;
        if (pos <= mid) update(2 * v, tl, mid, pos, val);
        else update(2 * v + 1, mid + 1, tr, pos, val);
        t[v] = t[2 * v] + t[2 * v + 1];
    }
}

int calc(int l, int r) {
    if (l <= r) return get(1, 0, n - 1, l, r);
    else return get(1, 0, n - 1, l, n - 1) + get(1, 0, n - 1, 0, r);
}

int nxt(int x, int j) {
    __typeof(s[x].begin()) it = s[x].lower_bound(j);
    if (it == s[x].end()) it = s[x].begin();
    return *it;
}

int main(){

    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d", a + i);
        b[i] = a[i];
    }

    sort(b, b + n);

    int cur = 0;
    ll ans = 0;

    for (int it = 0; it < n; it++) {
        int x = b[it];
        int j = nxt(x, cur);
        ans += calc(cur, j);
        update(1, 0, n - 1, j, 0);
        s[x].erase(j);
        cur = j;
    }

    cout << ans << endl;

    return 0;
}


#pragma comment(linker, "/STACK:64000000")
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <ctime>
#include <sstream>
#include <algorithm>
#include <functional>
#include <numeric>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>

using namespace std;

#define f first
#define s second
#define pb push_back
#define mp make_pair
#define ll long long
#define pii pair < int, int >
#define pll pair < long long, long long>
#define ull unsigned long long
#define y1 stupid_cmath
#define left stupid_left
#define right stupid_right
#define vi vector <int>
#define sz(a) (int)a.size()
#define forit(it, s) for(__typeof(s.begin()) it = s.begin(); it != s.end(); it++)
#define all(a) a.begin(), a.end()
#define sqr(x) ((x) * (x))

const int inf = (int)1e9;
const int mod = inf + 7;
const double eps = 1e-9;
const double pi = acos(-1.0);

int n, a[100100];
set<int> g[100100];
int b[100100];
int t[4 * 100100];
int pos = 0;

void build(int v, int tl, int tr) {
    if (tl == tr) t[v] = 1;
    else {
        int mid = (tl + tr) >> 1;
        build(2 * v, tl, mid);
        build(2 * v + 1, mid + 1, tr);
        t[v] = t[2 * v] + t[2 * v + 1];
    }
}

int get(int v, int tl, int tr, int l, int r) {
    if (l > tr || r < tl) return 0;
    if (l <= tl && tr <= r) return t[v];
    int mid = (tl + tr) >> 1;
    int ans1 = get(2 * v, tl, mid, l, r);
    int ans2 = get(2 * v + 1, mid + 1, tr, l, r);
    return ans1 + ans2;
}

void update(int v, int tl, int tr, int pos, int val) {
    if (tl == tr) t[v] = val;
    else {
        int mid = (tl + tr) >> 1;
        if (pos <= mid) update(2 * v, tl, mid, pos, val);
        else update(2 * v + 1, mid + 1, tr, pos, val);
        t[v] = t[2 * v] + t[2 * v + 1];
    }
}

int calc(int l, int r) {
    if (l <= r) return get(1, 0, n - 1, l, r);
    else return get(1, 0, n - 1, l, n - 1) + get(1, 0, n - 1, 0, r);
}

int nxt(int x, int j) {
    __typeof(s[x].begin()) it = s[x].lower_bound(j);
    if (it == s[x].end()) it = s[x].begin();
    return *it;
}

int main(){

    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d", a + i);
        b[i] = a[i];
    }

    sort(b, b + n);

    int cur = 0;
    ll ans = 0;

    for (int it = 0; it < n; it++) {
        int x = b[it];
        int j = nxt(x, cur);
        ans += calc(cur, j);
        update(1, 0, n - 1, j, 0);
        s[x].erase(j);
        cur = j;
    }

    cout << ans << endl;

    return 0;
}


#pragma comment(linker, "/STACK:64000000")
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <ctime>
#include <sstream>
#include <algorithm>
#include <functional>
#include <numeric>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>

using namespace std;

#define f first
#define s second
#define pb push_back
#define mp make_pair
#define ll long long
#define pii pair < int, int >
#define pll pair < long long, long long>
#define ull unsigned long long
#define y1 stupid_cmath
#define left stupid_left
#define right stupid_right
#define vi vector <int>
#define sz(a) (int)a.size()
#define forit(it, s) for(__typeof(s.begin()) it = s.begin(); it != s.end(); it++)
#define all(a) a.begin(), a.end()
#define sqr(x) ((x) * (x))

const int inf = (int)1e9;
const int mod = inf + 7;
const double eps = 1e-9;
const double pi = acos(-1.0);

int n, a[100100];
set<int> s[100100];
int b[100100];
int t[4 * 100100];
int pos = 0;

void build(int v, int tl, int tr) {
    if (tl == tr) t[v] = 1;
    else {
        int mid = (tl + tr) >> 1;
        build(2 * v, tl, mid);
        build(2 * v + 1, mid + 1, tr);
        t[v] = t[2 * v] + t[2 * v + 1];
    }
}

int get(int v, int tl, int tr, int l, int r) {
    if (l > tr || r < tl) return 0;
    if (l <= tl && tr <= r) return t[v];
    int mid = (tl + tr) >> 1;
    int ans1 = get(2 * v, tl, mid, l, r);
    int ans2 = get(2 * v + 1, mid + 1, tr, l, r);
    return ans1 + ans2;
}

void update(int v, int tl, int tr, int pos, int val) {
    if (tl == tr) t[v] = val;
    else {
        int mid = (tl + tr) >> 1;
        if (pos <= mid) update(2 * v, tl, mid, pos, val);
        else update(2 * v + 1, mid + 1, tr, pos, val);
        t[v] = t[2 * v] + t[2 * v + 1];
    }
}

int calc(int l, int r) {
    if (l <= r) return get(1, 0, n - 1, l, r);
    else return get(1, 0, n - 1, l, n - 1) + get(1, 0, n - 1, 0, r);
}

int nxt(int x, int j) {
    __typeof(s[x].begin()) it = s[x].lower_bound(j);
    if (it == s[x].end()) it = s[x].begin();
    return *it;
}

int main(){

    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d", a + i);
        b[i] = a[i];
    }

    sort(b, b + n);

    build(1, 0, n - 1);

    int cur = 0;
    ll ans = 0;

    for (int it = 0; it < n; it++) {
        int x = b[it];
        int j = nxt(x, cur);
        ans += calc(cur, j);
        update(1, 0, n - 1, j, 0);
        s[x].erase(j);
        cur = j;
    }

    cout << ans << endl;

    return 0;
}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
int n;
vector<int> e[100005];
struct node
{
    int val;int id;
}a[100005];
int cnt=0;

bool cmp(node x,node y)
{
    return x.val<y.val;
}

int main()
{
    while(~scanf("%d",&n))
    {
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i].val);
            a[i].id=i;
        }
        a[0].val=0;
        sort(a+1,a+n+1,cmp);
        for(int i=1;i<=n;i++)
        {
            if(a[i].val!=a[i-1].val)
                cnt++;
            e[cnt].push_back(a[i].id);
            //cout<<cnt<<":"<<a[i].id<<endl;
        }

        for(int i=1;i<=cnt;i++)
        {
            sort(e[i].begin(),e[i].end());
        }
        long long ans=0;
        int tans=n;

        int pre=n+1;
        for(int i=1;i<=cnt;i++)
        {
            if(e[i][0]<pre)
            {
                for(int j=e[i].size()-1;j>=0;j--)
                {
                    if(e[i][j]>pre)
                        tans--;
                    else
                    {
                        ans+=tans;
                        //cout<<i<<"~"<<tans<<endl;
                        pre=e[i][j];
                        tans-=(j+1);
                        break;
                    }
                }
            }
            else
            {
                tans-=e[i].size();
                pre=e[i][e[i].size()-1];
            }
        }
        printf("%lld\n",ans);
    }
}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int n;
struct node
{
    int val;
    int id;
}a[100005];

bool cmp(node x,node y)
{
    if(x.val==y.val)
        return x.id<y.id;
    else
        return x.val<y.val;
}

int main()
{
    while(~scanf("%d",&n))
    {
        for(int i=0;i<n;i++)
        {
            int tp;
            scanf("%d",&tp);
            a[i].id=i;
            a[i].val=tp;
        }
        sort(a,a+n,cmp);

        long long ans=0;
        int tans=n;
        int pre=n;
        for(int i=0;i<n;i++)
        {
            if(a[i].id<pre)
            {
                ans+=tans;
                tans--;
            }
            else
            {
                tans--;
            }
            pre=a[i].id;
        }
        printf("%lld\n",ans);
    }

}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int n;
struct node
{
    int val;
    int id;
}a[100005];

bool cmp(node x,node y)
{
    if(x.val==y.val)
        return x.id<y.id;
    else
        return x.val<y.val;
}

int main()
{
    while(~scanf("%d",&n))
    {
        for(int i=0;i<n;i++)
        {
            int tp;
            scanf("%d",&tp);
            a[i].id=i;
            a[i].val=tp;
        }
        sort(a,a+n,cmp);

        int ans=0;
        int tans=n;
        int pre=n;
        for(int i=0;i<n;i++)
        {
            if(a[i].id<pre)
            {
                ans+=tans;
                tans--;
            }
            else
            {
                tans--;
            }
            pre=a[i].id;
        }
        printf("%d\n",ans);
    }

}


#include <bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
struct lt
{
    int l,r;
    int mi,pos;
    int count;
};
lt rt[100010<<2];
int a[100010];
void updata(int i)
{
    rt[i].count=rt[i<<1].count+rt[i<<1|1].count;
    if(rt[i<<1].mi<=rt[i<<1|1].mi)
    {
        rt[i].mi=rt[i<<1].mi;
        rt[i].pos=rt[i<<1].pos;
    }
    else
    {
        rt[i].mi=rt[i<<1|1].mi;
        rt[i].pos=rt[i<<1|1].pos;
    }
}
void build(int i,int l,int r)
{
    rt[i].l=l;
    rt[i].r=r;
    if(l==r)
    {
        rt[i].count=1;
        rt[i].mi=a[l-1];
        rt[i].pos=l;
        return ;
    }
    int mid=(l+r)>>1;
    build(i<<1,l,mid);
    build(i<<1|1,mid+1,r);
    updata(i);
}
void dele(int i,int d)
{
    if(rt[i].l>d||rt[i].r<d)
        return ;
    if(rt[i].l==rt[i].r)
    {
        rt[i].mi=inf;
        rt[i].pos=-1;
        rt[i].count=0;
        return ;
    }
    dele(i<<1,d);
    dele(i<<1|1,d);
    updata(i);
}
int query_c(int i,int l,int r)
{
    if(rt[i].l>r||rt[i].r<l)
        return 0;
    if(rt[i].l>=l&&rt[i].r<=r)
        return rt[i].count;
    return query_c(i<<1,l,r)+query_c(i<<1|1,l,r);
}
pair<int,int> query_mi(int i,int l,int r)
{
    if(rt[i].l>r||rt[i].r<l)
        return pair<int,int>(inf,inf);
    if(rt[i].l>=l&&rt[i].r<=r)
        return pair<int,int>(rt[i].mi,rt[i].pos);
    return min(query_mi(i<<1,l,r),query_mi(i<<1|1,l,r));
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        for(int i=0; i<n; ++i)
            scanf("%d",a+i);
        build(1,1,n);
        int now=0;
        long long ans=0;
        for(int i=0; i<n; ++i)
        {
            int pos=rt[1].pos;
//            printf("%d %d\n",rt[1].mi,rt[1].pos);
            if(pos>now)
                ans+=query_c(1,now,pos);
            else
            {
                pair<int,int>temp=query_mi(1,now,n);
                if(temp.first==rt[1].mi)
                {
                    pos=temp.second;
                    ans+=query_c(1,now,pos);
                }
                else
                    ans+=query_c(1,1,pos)+query_c(1,now,n);
            }
            now=pos;
            dele(1,pos);
        }
        printf("%lld\n",ans);
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
struct lt
{
    int l,r;
    int mi,pos;
    int count;
};
lt rt[100010<<2];
int a[100010];
void updata(int i)
{
    rt[i].count=rt[i<<1].count+rt[i<<1|1].count;
    if(rt[i<<1].mi<=rt[i<<1|1].mi)
    {
        rt[i].mi=rt[i<<1].mi;
        rt[i].pos=rt[i<<1].pos;
    }
    else
    {
        rt[i].mi=rt[i<<1|1].mi;
        rt[i].pos=rt[i<<1|1].pos;
    }
}
void build(int i,int l,int r)
{
    rt[i].l=l;
    rt[i].r=r;
    if(l==r)
    {
        rt[i].count=1;
        rt[i].mi=a[l-1];
        rt[i].pos=l;
        return ;
    }
    int mid=(l+r)>>1;
    build(i<<1,l,mid);
    build(i<<1|1,mid+1,r);
    updata(i);
}
void dele(int i,int d)
{
    if(rt[i].l>d||rt[i].r<d)
        return ;
    if(rt[i].l==rt[i].r)
    {
        rt[i].mi=0x3f3f3f3f;
        rt[i].pos=-1;
        rt[i].count=0;
        return ;
    }
    dele(i<<1,d);
    dele(i<<1|1,d);
    updata(i);
}
int query_c(int i,int l,int r)
{
    if(rt[i].l>r||rt[i].r<l)
        return 0;
    if(rt[i].l>=l&&rt[i].r<=r)
        return rt[i].count;
    return query_c(i<<1,l,r)+query_c(i<<1|1,l,r);
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        for(int i=0; i<n; ++i)
            scanf("%d",a+i);
        build(1,1,n);
        int now=0;
        int ans=0;
        for(int i=0; i<n; ++i)
        {
            int pos=rt[1].pos;
//            printf("%d %d\n",rt[1].mi,rt[1].pos);
            if(pos>now)
                ans+=query_c(1,now,pos);
            else ans+=query_c(1,1,pos)+query_c(1,now,n);
            now=pos;
            dele(1,pos);
        }
        printf("%d\n",ans);
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
int a[100010];
int b[100010];
int nxsd(int l,int r)
{
    if(l>=r)
        return 0;
    int mid=(l+r)>>1;
    int ans=0,pos=l;
    ans+=nxsd(l,mid);
    ans+=nxsd(mid+1,r);
    int i=l,j=mid+1;
    while(i<=mid||j<=r)
    {
        if(i<=mid&&j<=r)
        {
            if(b[i]<=b[j])
                a[pos++]=b[i++];
            else
            {
                a[pos++]=b[j++];
                ans+=mid-i+1;
            }
        }
        else if(i<=mid)
            a[pos++]=b[i++];
        else a[pos++]=b[j++];
    }
    for(i=l;i<=r;++i)
        b[i]=a[i];
    return ans;
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        int mi=0x3f3f3f3f;
        int pos=0;
        int ans=0;
        for(int i=0; i<n; ++i)
        {
            scanf("%d",a+i);
            if(a[i]<mi)
            {
                mi=a[i];
                pos=i;
            }
        }
        ans+=pos+n;
        for(int i=0;i<n-pos;++i)
            b[i]=a[i+pos];
        for(int i=0;i<pos;++i)
            b[n-pos+i]=a[i];
        printf("%d\n",ans+nxsd(0,n-1));
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
struct lt
{
    int l,r;
    int mi,pos;
    int count;
};
lt rt[100010<<2];
int a[100010];
void updata(int i)
{
    rt[i].count=rt[i<<1].count+rt[i<<1|1].count;
    if(rt[i<<1].mi<=rt[i<<1|1].mi)
    {
        rt[i].mi=rt[i<<1].mi;
        rt[i].pos=rt[i<<1].pos;
    }
    else
    {
        rt[i].mi=rt[i<<1|1].mi;
        rt[i].pos=rt[i<<1|1].pos;
    }
}
void build(int i,int l,int r)
{
    rt[i].l=l;
    rt[i].r=r;
    if(l==r)
    {
        rt[i].count=1;
        rt[i].mi=a[l-1];
        rt[i].pos=l;
        return ;
    }
    int mid=(l+r)>>1;
    build(i<<1,l,mid);
    build(i<<1|1,mid+1,r);
    updata(i);
}
void dele(int i,int d)
{
    if(rt[i].l>d||rt[i].r<d)
        return ;
    if(rt[i].l==rt[i].r)
    {
        rt[i].mi=inf;
        rt[i].pos=-1;
        rt[i].count=0;
        return ;
    }
    dele(i<<1,d);
    dele(i<<1|1,d);
    updata(i);
}
int query_c(int i,int l,int r)
{
    if(rt[i].l>r||rt[i].r<l)
        return 0;
    if(rt[i].l>=l&&rt[i].r<=r)
        return rt[i].count;
    return query_c(i<<1,l,r)+query_c(i<<1|1,l,r);
}
pair<int,int> query_mi(int i,int l,int r)
{
    if(rt[i].l>r||rt[i].r<l)
        return pair<int,int>(inf,inf);
    if(rt[i].l>=l&&rt[i].r<=r)
        return pair<int,int>(rt[i].mi,rt[i].pos);
    return min(query_mi(i<<1,l,r),query_mi(i<<1|1,l,r));
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        for(int i=0; i<n; ++i)
            scanf("%d",a+i);
        build(1,1,n);
        int now=0;
        int ans=0;
        for(int i=0; i<n; ++i)
        {
            int pos=rt[1].pos;
//            printf("%d %d\n",rt[1].mi,rt[1].pos);
            if(pos>now)
                ans+=query_c(1,now,pos);
            else
            {
                pair<int,int>temp=query_mi(1,now,n);
                if(temp.first==rt[1].mi)
                {
                    pos=temp.second;
                    ans+=query_c(1,now,pos);
                }
                else
                    ans+=query_c(1,1,pos)+query_c(1,now,n);
            }
            now=pos;
            dele(1,pos);
        }
        printf("%d\n",ans);
    }
    return 0;
}


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

#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds ;

#define ordered_set tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>

const int mx = 1e5 + 69 ;

int n , vis[mx] , a[mx] , siz[mx] ;

vector<int> v[mx] ;

int bs(int key , int mn)
{
    int low = 0 , high = siz[mn] - 1 ;
    while(low<high)
    {
        int mid = (low+high+1)/2 ;
        if(v[mn][mid]<=key) low = mid ;
        else high = mid - 1 ;
    }
    return v[mn][low] ;
}

int main()
{
    scanf("%d",&n) ;
    set<int> s ;
    ordered_set o ;
    for(int i = 1 ; i <= n ; ++i) scanf("%d",&a[i]) , s.insert(a[i]) , o.insert(i) , v[a[i]].push_back(i) , ++siz[a[i]] , vis[a[i]] = i ;
    int cur = 1 , o_siz = n ;
    long long ans = 0 ;
    while(!s.empty())
    {
        int num = *s.begin() ;
        int ind = bs(cur,num) , cur_ind = o.order_of_key(cur) , usx = 0 ;
        if(ind!=cur && ind<cur)
        {
            int dis_ind = o.order_of_key(ind) ;
            ans += 1LL*(o_siz-cur_ind+1+dis_ind) ;
            usx = ind ;
        }
        else
        {
            int dis_ind = o.order_of_key(vis[num]) ;
            ans += 1LL*(dis_ind-cur_ind+1) ;
            usx = vis[num] ;
        }
        auto it = o.find(usx) ;
        ++it ;
        cur = *it ;
        int kx = siz[num] - 1 ;
        while(kx>=0)
        {
            o.erase(o.find(v[num][kx])) ;
            --kx ;
            --o_siz ;
        }
        s.erase(num) ;
    }
    printf("%lld\n",ans) ;
    return 0 ;
}


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

const int mx = 1e5 + 69 ;

int vis[mx] , a[mx] , n ;

vector<int> v[mx] ;

int main()
{
    scanf("%d",&n) ;
    set<int> s ;
    for(int i = 1 ; i <= n ; ++i) scanf("%d",&a[i]) , v[a[i]].push_back(i) , s.insert(a[i]) , ++vis[a[i]] ;
    int cur = 1 , cnt = 0 ;
    long long ans = 0 ;
    while(!s.empty())
    {
        int num = *s.begin() , ase = 0 , ot = 0 ;
        for(int i = 0 ; i < vis[num] ; ++i)
        {
            if(v[num][i]>=cur)
            {
                cur = v[num][i] ;
                ++cnt ;
                v[num][i] = -1 ;
            }
        }
        for(int i = 0 ; i < vis[num] ; ++i)
        {
            if(v[num][i]!=-1)
            {
                ase = 1 ;
                ++ot ;
                cur = v[num][i] ;
                v[num][i] = -1 ;
            }
        }
        if(ase)
        {
            ans += 1LL*n ;
            n = n - cnt ;
            cnt = ot ;
        }
        s.erase(num) ;
    }
    printf("%lld\n",ans+(1LL*n)) ;
    return 0 ;
}


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

#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds ;

#define ordered_set tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>

const int mx = 1e5 + 69 ;

int n , vis[mx] , a[mx] , siz[mx] ;

vector<int> v[mx] ;

int bs(int key , int mn)
{
    int low = 0 , high = siz[mn] - 1 ;
    while(low<high)
    {
        int mid = (low+high)/2 ;
        if(v[mn][mid]<=key) low = mid ;
        else high = mid - 1 ;
    }
    return v[mn][low] ;
}

int main()
{
    scanf("%d",&n) ;
    set<int> s ;
    ordered_set o ;
    for(int i = 1 ; i <= n ; ++i) scanf("%d",&a[i]) , s.insert(a[i]) , o.insert(i) , v[a[i]].push_back(i) , ++siz[a[i]] , vis[a[i]] = i ;
    int cur = 1 , o_siz = n ;
    long long ans = 0 ;
    while(!s.empty())
    {
        int num = *s.begin() ;
        int ind = bs(cur,num) , cur_ind = o.order_of_key(cur) , usx = 0 ;
        if(ind!=cur && ind<cur)
        {
            int dis_ind = o.order_of_key(ind) ;
            ans += 1LL*(o_siz-cur_ind+1+dis_ind) ;
            usx = ind ;
        }
        else
        {
            int dis_ind = o.order_of_key(vis[num]) ;
            ans += 1LL*(dis_ind-cur_ind+1) ;
            usx = vis[num] ;
        }
        auto it = o.find(usx) ;
        ++it ;
        cur = *it ;
        int kx = siz[num] - 1 ;
        while(kx>=0)
        {
            o.erase(o.find(v[num][kx])) ;
            --kx ;
            --o_siz ;
        }
        s.erase(num) ;
    }
    printf("%lld\n",ans) ;
    return 0 ;
}


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

 const int MaxN = 5e6 + 1, MaxT = 4 * MaxN;
 int ans;
 int t[MaxT];
 int N = 5e6;
 int a[MaxN];
 int inf = 2e9;
 void build(int v,int tl,int tr){
    if(tl == tr)
            t[v] = a[tl]; else{
        int tm = (tl + tr) >> 1,
            one = (v << 1),
            two = (one + 1);
            build(one, tl, tm);
            build(two, tm + 1, tr);
            t[v] = min(t[one], t[two]);
    }
 }

 void up(int v,int tl,int tr,int pos,int val){
    if(tl > pos || tr < pos) return;
    if(tl == tr) t[v] = val; else{
        int tm = (tl + tr) >> 1,
            one = v << 1,
            two = one | 1;
        up(one, tl, tm, pos, val);
        up(two, tm + 1, tr, pos, val);
    }
 }

 int get(int v,int tl,int tr,int l,int r){
    if(tl > r || tr < l) return inf;
    if(tl >= l && tr <= r) return t[v];
    int tm = (tl + tr) >> 1,
        one = v << 1,
        two = one | 1;
    return min(get(one, tl, tm, l, r), get(two, tm + 1, tr, l, r));
 }

 main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    for(int i = 1; i <= N; ++i) a[i] = inf;

    int n;
    cin >> n;
    for(int i = 1; i <= n; ++i){
        cin >> a[i];
    }

    build(1, 1, N);

    int l = 1,
    r = n;
    long long ans = 0;

    while(l <= r){
        if(get(1, 1, N, l, r) != a[l]){
            ++r;
            up(1, 1, N, r, a[l]);
        }
        ++l;
        ++ans;
    }

    cout << ans << '\n';

    return 0;
 }


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

 const int MaxN = 5e6 + 1, MaxT = 4 * MaxN;
 int ans;
 int t[MaxT];
 int N = 5e6;
 int a[MaxN];
 int inf = 2e9;
 void build(int v,int tl,int tr){
    if(tl == tr)
            t[v] = a[tl]; else{
        int tm = (tl + tr) >> 1,
            one = (v << 1),
            two = (one + 1);
            build(one, tl, tm);
            build(two, tm + 1, tr);
            t[v] = min(t[one], t[two]);
    }
 }

 void up(int v,int tl,int tr,int pos,int val){
    if(tl > pos || tr < pos) return;
    if(tl == tr) t[v] = val; else{
        int tm = (tl + tr) >> 1,
            one = v << 1,
            two = one | 1;
        up(one, tl, tm, pos, val);
        up(two, tm + 1, tr, pos, val);
    }
 }

 int get(int v,int tl,int tr,int l,int r){
    if(tl > r || tr < l) return inf;
    if(tl >= l && tr <= r) return t[v];
    int tm = (tl + tr) >> 1,
        one = v << 1,
        two = one | 1;
    return min(get(one, tl, tm, l, r), get(two, tm + 1, tr, l, r));
 }

 main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    for(int i = 1; i <= N; ++i) a[i] = inf;

    int n;
    cin >> n;
    for(int i = 1; i <= n; ++i){
        cin >> a[i];
    }

    build(1, 1, N);

    int l = 1,
    r = n;
    long long ans = 0;

    while(l <= r){
        if(get(1, 1, N, l, r) != a[l]){
            a[++r] = a[l];
            up(1, 1, N, r, a[l]);
        }
        ++l;
        ++ans;
    }

    cout << ans << '\n';

    return 0;
 }


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

 const int MaxN = 5e6 + 121, N = 1e5, inf = 1e9;
 int a[MaxN];
 pair<int,int> t[MaxN];
 int n;

 void build(int v,int tl,int tr){
    if(tl == tr) t[v] = {a[tl],tl}; else{
        int tm = (tl + tr) >> 1,
            one = v << 1,
            two = one | 1;
        build(one, tl, tm);
        build(two, tm + 1, tr);
        if(t[one].first <= t[two].first) t[v] = t[one]; else t[v] = t[two];
    }
 }

 void up(int v,int tl,int tr,int pos){
    if(tl > pos || pos < tr) return;
    if(tl == tr){
        t[v].first = inf;
        return;
    }
    int tm = (tl + tr) >> 1,
        one = v << 1,
        two = one | 1;
    up(one, tl, tm, pos);
    up(two, tm + 1, tr, pos);
    if(t[one].first <= t[two].first) t[v] = t[one]; else t[v] = t[two];
 }

 pair<int,int> get(int v,int tl,int tr,int l,int r){
    if(tl > r || tr < l) return {inf,inf};
    if(tl >= l && tr <= r) return t[v];
    int tm = (tl + tr) >> 1,
        one = v << 1,
        two = one + 1;
    pair<int,int> ans1 = get(one, tl, tm, l, r),
                  ans2 = get(two, tm + 1, tr, l, r);
    if(ans1.first <= ans2.first) return ans1;
    return ans2;
 }

 inline int GetMin(int l,int r){
    int mn = a[l];
    for(int i = l + 1; i <= r; ++i)
        if(a[i] < mn) mn = a[i];
    return mn;
 }

 int stupidSolve(){
    int l = 1,
        r = n;

    int ans = 0;
    while(l <= r){
        if(GetMin(l, r) != a[l]) a[++r] = a[l];
        ++l;
        ++ans;
    }

    return ans;
 }

 int GoodSolve(){
    int ans = 0;
    build(1, 1, n);
    int cnt = 0, l = 1;
    int CountWas = 0;
    while(cnt < n){
        pair<int,int> Ans = get(1, 1, n, l, n);
        if(Ans.first == inf){
            l = 1;
            CountWas = 0;
            Ans = get(1, 1, n, l, n);
        }
        ans += Ans.second - CountWas;
        ++CountWas;
        ++l;
        ++cnt;
        up(1, 1, n, Ans.second);
    }
    return ans;
 }
 int MyRand(int md,int add = 0){
    int ans = 0;
    for(int i = 0; i <= 32; ++i)
         ans = (ans + ((1ll << i) * rand() % 2) % md) % md;
    return ans + add;
 }
 main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    //srand(time(NULL));

    //n = MyRand(100000, 1);

    cin >> n;
    for(int i = 1; i <= n; ++i){
        cin >> a[i];
        //a[i] = MyRand(100000, 1);
    }

    cout << GoodSolve() << '\n';
    //cout << (stupidSolve() == GoodSolve()) << '\n';

    return 0;
 }


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

 const int MaxN = 5e6 + 121, N = 1e5, inf = 1e9;
 int a[MaxN];
 pair<int,int> t[MaxN];
 int n;

 void build(int v,int tl,int tr){
    if(tl == tr) t[v] = {a[tl],tl}; else{
        int tm = (tl + tr) >> 1,
            one = v << 1,
            two = one | 1;
        build(one, tl, tm);
        build(two, tm + 1, tr);
        if(t[one].first <= t[two].first) t[v] = t[one]; else t[v] = t[two];
    }
 }

 void up(int v,int tl,int tr,int pos){
    if(tl > pos || pos < tr) return;
    if(tl == tr){
        t[v].first = inf;
        return;
    }
    int tm = (tl + tr) >> 1,
        one = v << 1,
        two = one | 1;
    up(one, tl, tm, pos);
    up(two, tm + 1, tr, pos);
    if(t[one].first <= t[two].first) t[v] = t[one]; else t[v] = t[two];
 }

 pair<int,int> get(int v,int tl,int tr,int l,int r){
    if(tl > r || tr < l) return {inf,inf};
    if(tl >= l && tr <= r) return t[v];
    int tm = (tl + tr) >> 1,
        one = v << 1,
        two = one + 1;
    pair<int,int> ans1 = get(one, tl, tm, l, r),
                  ans2 = get(two, tm + 1, tr, l, r);
    if(ans1.first <= ans2.first) return ans1;
    return ans2;
 }

 inline int GetMin(int l,int r){
    int mn = a[l];
    for(int i = l + 1; i <= r; ++i)
        if(a[i] < mn) mn = a[i];
    return mn;
 }

 int stupidSolve(){
    int l = 1,
        r = n;

    int ans = 0;
    while(l <= r){
        if(GetMin(l, r) != a[l]) a[++r] = a[l];
        ++l;
        ++ans;
    }

    return ans;
 }

 int GoodSolve(){
    int ans = 0;
    int cnt = 0, l = 1;
    int CountWas = 0;
    while(cnt < n){
        pair<int,int> Ans = get(1, 1, n, l, n);
        if(Ans.first == inf){
            l = 1;
            CountWas = 0;
            Ans = get(1, 1, n, l, n);
        }
        ans += Ans.second - CountWas;
        ++CountWas;
        ++l;
        ++cnt;
        up(1, 1, n, Ans.second);
    }
    return ans;
 }
 int MyRand(int md,int add = 0){
    int ans = 0;
    for(int i = 0; i <= 50; ++i)
         ans = (ans + ((1ll << i) * (rand() % 2)) % md) % md;
    return ans + add;
 }
 main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    //srand(time(NULL));

 //   n = 10;

  //  cout << n << endl;

    cin >> n;
    for(int i = 1; i <= n; ++i){
        cin >> a[i];
        //a[i] = MyRand(30, 1);
    }

    //for(int i = 1; i <= n; ++i) cout << a[i] << ' '; cout << endl;
    //build(1, 1, n);
    cout << stupidSolve() << endl;
    //cout << GoodSolve() << '\n';
    //cout << (stupidSolve() == GoodSolve()) << '\n';

    return 0;
 }


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

 const int MaxN = 5e6 + 121, N = 1e5 + 10, inf = 1e9;
 int a[MaxN];
 pair<int,int> t[MaxN];
 int n,t2[MaxN];

 void build(int v,int tl,int tr){
    if(tl == tr) t[v] = {a[tl],tl}; else{
        int tm = (tl + tr) >> 1,
            one = v << 1,
            two = one | 1;
        build(one, tl, tm);
        build(two, tm + 1, tr);
        if(t[one].first <= t[two].first) t[v] = t[one]; else t[v] = t[two];
    }
 }

 void up(int v,int tl,int tr,int pos){
    //cout << "IN " << v << ' ' << tl << ' ' << tr << ' ' << pos << endl;
    if(tl > pos || tr < pos) return;
    ++t2[v];
    if(tl == tr){
        t[v].first = inf;
        return;
    }
    int tm = (tl + tr) >> 1,
        one = v << 1,
        two = one | 1;
    up(one, tl, tm, pos);
    up(two, tm + 1, tr, pos);
    if(t[one].first <= t[two].first) t[v] = t[one]; else t[v] = t[two];
    //cout << "OUT " << v << ' ' << tl << ' ' << tr << ' ' << pos << endl;
 }

 pair<int,int> get(int v,int tl,int tr,int l,int r){
    if(tl > r || tr < l) return {inf,inf};
    if(tl >= l && tr <= r) return t[v];
    int tm = (tl + tr) >> 1,
        one = v << 1,
        two = one + 1;
    pair<int,int> ans1 = get(one, tl, tm, l, r),
                  ans2 = get(two, tm + 1, tr, l, r);
    if(ans1.first <= ans2.first) return ans1;
    return ans2;
 }

 int get2(int v,int tl,int tr,int l,int r){
    if(tl > r || tr < l) return 0;
    if(tl >= l && tr <= r) return t2[v];
    int tm = (tl + tr) >> 1,
        one = v << 1,
        two = one | 1;
    return get2(one, tl, tm, l, r) + get2(two, tm + 1, tr, l, r);
 }

 inline int GetMin(int l,int r){
    int mn = a[l];
    for(int i = l + 1; i <= r; ++i)
        if(a[i] < mn) mn = a[i];
    return mn;
 }

 int stupidSolve(){
    int l = 1,
        r = n;

    int ans = 0;
    while(l <= r){
        if(GetMin(l, r) != a[l]) a[++r] = a[l];
        ++l;
        ++ans;
    }

    return ans;
 }

 int GoodSolve(){
    int ans = 0;
    int cnt = 0, l = 1;
    //int CountWas = 0;
    int Count = 0;
    while(cnt < n){
        pair<int,int> Ans = get(1, 1, n, l, n);
        if(Ans.first > t[1].first){
            ans += n - l + 1 - get2(1, 1, n, l, n);
            //cout << "add2 " << n - l + 1 << '\n';
            l = 1;
        //    CountWas = 0;
            Ans = get(1, 1, n, l, n);
        }
        //cout << "add " << (++Count) << ' ' << Ans.second - CountWas <<' ' << Ans.second << '\n';
        ans += (Ans.second - l + 1) - get2(1, 1, n,l, Ans.second);
      //  CountWas = Ans.second;
        l = Ans.second + 1;
        ++cnt;
        up(1, 1, n, Ans.second);
    }
    return ans;
 }
 int MyRand(int md,int add = 0){
    int ans = 0;
    for(int i = 0; i <= 50; ++i)
         ans = (ans + ((1ll << i) * (rand() % 2)) % md) % md;
    return ans + add;
 }
 main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

   // srand(time(NULL));

   // n = 1000;

    //cout << n << endl;

    cin >> n;
    for(int i = 1; i <= n; ++i){
        cin >> a[i];
      //  a[i] = MyRand(30000, 1);
    }

    //for(int i = 1; i <= n; ++i) cout << a[i] << ' '; cout << endl;
    build(1, 1, n);
    //cout << stupidSolve() << endl;
    cout << GoodSolve() << '\n';
   // cout << (stupidSolve() == GoodSolve()) << '\n';

    return 0;
 }


#include <bits/stdc++.h>

using namespace std;

#define ll long long
#define pb push_back
#define F first
#define S second
#define make0(a) memset(a,0,sizeof(a))
#define make1(a) memset(a,-1,sizeof(a))
#define all(v) begin(v),end(v)
#define allr(v) v.rbegin(),v.rend()
#define pi pair <int,int>
#define pll pair <ll,ll>
#define cases int t; cin >> t; while(t--)
#define fast_cin() ios_base::sync_with_stdio(0)

const int mod = 1e9+7;
const int maxn = 1e5+10;

#define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
    cerr << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
    const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
#else
#define trace(...)
#endif

int stree[maxn*4];

void makeTree(int i, int j, int sidx)
{
	if(i == j)
	{
		stree[sidx] = 0;
		return;
	}
	int mid = (i+j)/2;
	makeTree(i,mid,sidx*2);
	makeTree(mid+1,j,sidx*2+1);
	stree[sidx] = stree[sidx*2]+stree[sidx*2+1];
}

int l,r;
int idx,val;

int query(int i, int j, int sidx)
{
	// trace(i, j);
	if(r < l)
		return 0;
	if(i > r or j < l)
		return 0;
	if(i >= l and j <= r)
		return stree[sidx];
	int mid = (i+j)/2;
	return query(i,mid,sidx*2) + query(mid+1,j,sidx*2+1);
}

void update(int i, int j, int sidx)
{
	if(idx > j or idx < i)
		return;
	if(i == j)
	{
		stree[sidx] = val;
		return;
	}
	int mid = (i+j)/2;
	update(i,mid,sidx*2);
	update(mid+1,j,sidx*2+1);
	stree[sidx] = stree[sidx*2] + stree[sidx*2+1];
}

int main()
{
	fast_cin();
	int N;
	cin >> N;
	pi A[N+1];
	for(int i=1;i<=N;i++)
	{
		cin >> A[i].F;
		A[i].S = i;
	}
	sort(A+1,A+N+1);
	// for(int i=1;i<=N;i++)
	// 	cout << A[i].S << endl;

	int P[N+1];
	for(int i=1;i<=N;i++)
		P[i] = A[i].S;
	// for(int i=1;i<=N;i++)
	// 	cerr << P[i] << " ";
	int ct = 0;
	int last = 1;
	ll ans = 0;
	// cerr << ans << endl;
	for(int i=1;i<=N;i++)
	{
		// trace(ans);
		int curr = P[i];
		if(curr >= last)
		{
			l = last;
			r = curr-1;
			int done = query(1, N, 1);
			// cerr << last << ' ' << curr << ' ' << done << ' ' << ans << endl;
			ans += (curr - last - done + 1)*1ll;
		}
		else
		{
			l = last;
			r = N;
			int done = query(1, N, 1);
			// trace(l, r, done);
			l = 1;
			r = curr-1;
			done += query(1, N, 1);
			int diff = N - last + 1;
			diff += curr;
			// cerr << last << ' ' << curr << ' ' << done << ' ' << ans << endl;
			ans += (diff - done)*1ll;
		}
		idx = curr;
		val = 1;
		last = curr + 1;
		// trace(idx);
		update(1, N, 1);
		if(last == N+1)
			last = 1;
	}
	cout << ans << endl;

	return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define ll long long
#define pb push_back
#define F first
#define S second
#define make0(a) memset(a,0,sizeof(a))
#define make1(a) memset(a,-1,sizeof(a))
#define all(v) begin(v),end(v)
#define allr(v) v.rbegin(),v.rend()
#define pi pair <int,int>
#define pll pair <ll,ll>
#define cases int t; cin >> t; while(t--)
#define fast_cin() ios_base::sync_with_stdio(0)

const int mod = 1e9+7;
const int maxn = 1e5+10;

#define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
    cerr << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
    const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
#else
#define trace(...)
#endif

int stree[maxn*4];

void makeTree(int i, int j, int sidx)
{
	if(i == j)
	{
		stree[sidx] = 0;
		return;
	}
	int mid = (i+j)/2;
	makeTree(i,mid,sidx*2);
	makeTree(mid+1,j,sidx*2+1);
	stree[sidx] = stree[sidx*2]+stree[sidx*2+1];
}

int l,r;
int idx,val;

int query(int i, int j, int sidx)
{
	// trace(i, j);
	if(r < l)
		return 0;
	if(i > r or j < l)
		return 0;
	if(i >= l and j <= r)
		return stree[sidx];
	int mid = (i+j)/2;
	return query(i,mid,sidx*2) + query(mid+1,j,sidx*2+1);
}

void update(int i, int j, int sidx)
{
	if(idx > j or idx < i)
		return;
	if(i == j)
	{
		stree[sidx] = val;
		return;
	}
	int mid = (i+j)/2;
	update(i,mid,sidx*2);
	update(mid+1,j,sidx*2+1);
	stree[sidx] = stree[sidx*2] + stree[sidx*2+1];
}

int glob = 1;

int dist(int a, int b)
{
	if(a >= b)
		return a-b;
	else
	{
		return (1000000-b+1) + a;
	}
}

bool CP(int a, int b)
{
	return dist(a, glob) < dist(b, glob);
}

int main()
{
	fast_cin();
	int N;
	cin >> N;
	pi A[N+1];
	int B[N+1];
	for(int i=1;i<=N;i++)
	{
		cin >> A[i].F;
		B[i] = A[i].F;
		A[i].S = i;
	}
	sort(A+1,A+N+1);
	// for(int i=1;i<=N;i++)
	// 	cout << A[i].S << endl;

	int P[N+1];
	for(int i=1;i<=N;i++)
		P[i] = A[i].S;
	// for(int i=1;i<=N;i++)
	// 	cerr << P[i] << " ";
	// cerr << endl;
	int ct = 0;
	int last = 1;
	ll ans = 0;
	// cerr << ans << endl;
	bool done[100000+1];
	make0(done);
	for(int i=1;i<=N;i++)
	{
		if(done[B[P[i]]] == false)
		{
			// cerr << "HERE\n";
			int j;
			for(j=i;j<=N;j++)
			{
				if(j == N+1)
					break;
				if(B[P[i]] != B[P[j]])
					break;
				// cerr << P[j] << "	" << dist(P[j],last) << endl;
			}
			glob = last;
			sort(P+i, P+j, CP);
			done[B[P[i]]] = true;
		}
		// cerr << i << ' ' << j << endl;
		// for(int j=1;j<=N;j++)
		// 	cerr << P[j] << " ";
		// cerr << endl;
		int curr = P[i];
		if(curr >= last)
		{
			l = last;
			r = curr-1;
			int done = query(1, N, 1);
			// cerr << last << ' ' << curr << ' ' << done << ' ' << ans << endl;
			ans += (curr - last - done + 1)*1ll;
		}
		else
		{
			l = last;
			r = N;
			int done = query(1, N, 1);
			// trace(l, r, done);
			l = 1;
			r = curr-1;
			done += query(1, N, 1);
			int diff = N - last + 1;
			diff += curr;
			// cerr << last << ' ' << curr << ' ' << done << ' ' << ans << endl;
			ans += (diff - done)*1ll;
		}
		idx = curr;
		val = 1;
		last = curr + 1;
		// trace(idx);
		update(1, N, 1);
		if(last == N+1)
			last = 1;
	}
	cout << ans << endl;

	return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define ll long long
#define pb push_back
#define F first
#define S second
#define make0(a) memset(a,0,sizeof(a))
#define make1(a) memset(a,-1,sizeof(a))
#define all(v) begin(v),end(v)
#define allr(v) v.rbegin(),v.rend()
#define pi pair <int,int>
#define pll pair <ll,ll>
#define cases int t; cin >> t; while(t--)
#define fast_cin() ios_base::sync_with_stdio(0)

const int mod = 1e9+7;
const int maxn = 1e5+10;

#define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
    cerr << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
    const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
#else
#define trace(...)
#endif

int stree[maxn*4];

void makeTree(int i, int j, int sidx)
{
	if(i == j)
	{
		stree[sidx] = 0;
		return;
	}
	int mid = (i+j)/2;
	makeTree(i,mid,sidx*2);
	makeTree(mid+1,j,sidx*2+1);
	stree[sidx] = stree[sidx*2]+stree[sidx*2+1];
}

int l,r;
int idx,val;

int query(int i, int j, int sidx)
{
	// trace(i, j);
	if(r < l)
		return 0;
	if(i > r or j < l)
		return 0;
	if(i >= l and j <= r)
		return stree[sidx];
	int mid = (i+j)/2;
	return query(i,mid,sidx*2) + query(mid+1,j,sidx*2+1);
}

void update(int i, int j, int sidx)
{
	if(idx > j or idx < i)
		return;
	if(i == j)
	{
		stree[sidx] = val;
		return;
	}
	int mid = (i+j)/2;
	update(i,mid,sidx*2);
	update(mid+1,j,sidx*2+1);
	stree[sidx] = stree[sidx*2] + stree[sidx*2+1];
}

int glob = 1;

int dist(int a, int b)
{
	if(a >= b)
		return a-b;
	else
	{
		return (1000000-b+1) + a;
	}
}

bool CP(int a, int b)
{
	return dist(a, glob) < dist(b, glob);
}

int main()
{
	fast_cin();
	int N;
	cin >> N;
	pi A[N+1];
	int B[N+1];
	for(int i=1;i<=N;i++)
	{
		cin >> A[i].F;
		B[i] = A[i].F;
		A[i].S = i;
	}
	sort(A+1,A+N+1);
	// for(int i=1;i<=N;i++)
	// 	cout << A[i].S << endl;

	int P[N+1];
	for(int i=1;i<=N;i++)
		P[i] = A[i].S;
	// for(int i=1;i<=N;i++)
	// 	cerr << P[i] << " ";
	// cerr << endl;
	int ct = 0;
	int last = 1;
	ll ans = 0;
	// cerr << ans << endl;
	bool done[N+1];
	make0(done);
	for(int i=1;i<=N;i++)
	{
		if(done[B[P[i]]] == false)
		{
			// cerr << "HERE\n";
			int j;
			for(j=i;j<=N;j++)
			{
				if(B[P[i]] != B[P[j]])
					break;
				// cerr << P[j] << "	" << dist(P[j],last) << endl;
			}
			glob = last;
			sort(P+i, P+j, CP);
			done[B[P[i]]] = true;
		}
		// cerr << i << ' ' << j << endl;
		// for(int j=1;j<=N;j++)
		// 	cerr << P[j] << " ";
		// cerr << endl;
		int curr = P[i];
		if(curr >= last)
		{
			l = last;
			r = curr-1;
			int done = query(1, N, 1);
			// cerr << last << ' ' << curr << ' ' << done << ' ' << ans << endl;
			ans += (curr - last - done + 1)*1ll;
		}
		else
		{
			l = last;
			r = N;
			int done = query(1, N, 1);
			// trace(l, r, done);
			l = 1;
			r = curr-1;
			done += query(1, N, 1);
			int diff = N - last + 1;
			diff += curr;
			// cerr << last << ' ' << curr << ' ' << done << ' ' << ans << endl;
			ans += (diff - done)*1ll;
		}
		idx = curr;
		val = 1;
		last = curr + 1;
		// trace(idx);
		update(1, N, 1);
		if(last == N+1)
			last = 1;
	}
	cout << ans << endl;

	return 0;
}