#include <bits/stdc++.h>
using namespace std;
const int INF = 1000000001;
int main() {
  int n;
  cin >> n;
  vector<int> a(n);
  for (int i = 0; i < n; i++) {
    cin >> a[i];
  }
  int s = sqrt(n) + 1;
  vector<int> sz(2 * s), top(2 * s), p, nextp;
  int i = 0, j = 2 * s - 1;
  int ans = 0;
  p.push_back(-1);
  for (int y = 0; y < n; y++) {
    int r = -1;
    int l = -1;
    if (p[0] == -1) r = 0;
    for (int x = 0; x < 2 * s; x++) {
      top[x] = INF;
      sz[x] = 0;
    }
    for (int x = 0; x < n; x++) {
      if (r + 1 < p.size() && a[x] == p[r + 1]) {
        r++;
        continue;
      } else if (r == -1 || a[x] < p[r] || (l >= j && a[x] > top[j])) {
        continue;
      }
      int h;
      if (l == -1 || a[x] > top[l]) {
        l++;
        h = l;
      } else {
        h = lower_bound(top.begin(), top.end(), a[x]) - top.begin();
      }
      top[h] = a[x];
      sz[h]++;
    }
    if (l < 2 * s - 1) {
      ans += l + 1;
      break;
    }
    int nexti;
    for (int x = 2 * s - 1; x >= s; x--) {
      if (sz[x] <= s) {
        nexti = x;
        break;
      }
    }
    nextp.clear();
    r = -1;
    l = -1;
    if (p[0] == -1) r = 0;
    for (int x = 0; x < 2 * s; x++) {
      top[x] = INF;
      sz[x] = 0;
    }
    for (int x = 0; x < n; x++) {
      if (r + 1 < p.size() && a[x] == p[r + 1]) {
        r++;
        continue;
      } else if (r == -1 || a[x] < p[r] || (l >= j && a[x] > top[j])) {
        continue;
      }
      int h;
      if (l == -1 || a[x] > top[l]) {
        l++;
        h = l;
      } else {
        h = lower_bound(top.begin(), top.end(), a[x]) - top.begin();
      }
      if (h == nexti) nextp.push_back(a[x]);
      top[h] = a[x];
      sz[h]++;
    }
    p = nextp;
    i = 0;
    j = 2 * s - 1;
    ans += nexti + 1;
  }
  cout << ans << endl;
}
