/*input
6
6 5 4 3 2 1
*/
#include <bits/stdc++.h>
using namespace std;

typedef priority_queue<int, vector<int>, greater<int> > Dat;
queue<Dat> q;

void Merge(Dat &a, Dat &b) {
	if(a.size() < b.size()) a.swap(b);
	while(b.size()) a.push(b.top()), b.pop();
}

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

	vector<int> a(n);
	for(int i = 0; i < n; ++i) {
		scanf("%d", &a[i]);
		Dat cur; cur.push(a[i]);
		q.push(cur);
	}

	sort(a.begin(), a.end());
	long long Ans = 0;
	for(int i = 0; i < n; ++i) {
		Dat cur = std::move(q.front()); q.pop();

		while(cur.top() != a[i])
			Merge(cur, q.front()), q.pop();

		cur.pop();
		if(cur.size()) Ans += cur.size(), q.push(std::move(cur));
	}
	printf("%lld\n", Ans);
}
