1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <algorithm> 5 using namespace std; 6 typedef long long LL; 7 8 #define ll x * 2 9 #define rr x * 2 + 1 10 11 const int MAXN = 200010; 12 13 LL tree[MAXN * 4]; 14 int maxt[MAXN * 4], mint[MAXN * 4]; 15 int a[MAXN], n; 16 17 int head[MAXN], lcnt; 18 int pos[MAXN], next[MAXN]; 19 20 void init() { 21 memset(head, 0, (n + 1) * sizeof(int)); 22 lcnt = 1; 23 } 24 25 void add_link(int x, int i) { 26 pos[lcnt] = i; next[lcnt] = head[x]; head[x] = lcnt++; 27 } 28 29 void build(int x, int left, int right) { 30 if(left == right) tree[x] = maxt[x] = mint[x] = n - left + 1; 31 else { 32 int mid = (left + right) >> 1; 33 if(left <= mid) build(ll, left, mid); 34 if(mid < right) build(rr, mid + 1, right); 35 tree[x] = tree[ll] + tree[rr]; 36 maxt[x] = max(maxt[ll], maxt[rr]); 37 mint[x] = min(mint[ll], mint[rr]); 38 } 39 } 40 41 void update(int x, int left, int right, int a, int b, int val) { 42 if(a <= left && right <= b && mint[x] >= val) { 43 tree[x] = LL(val) * (right - left + 1); 44 maxt[x] = mint[x] = val; 45 } 46 else { 47 if(right == left) return ; 48 int mid = (left + right) >> 1; 49 if(maxt[x] == mint[x]) { 50 maxt[ll] = mint[ll] = maxt[x]; 51 tree[ll] = LL(mid - left + 1) * maxt[x]; 52 maxt[rr] = mint[rr] = maxt[x]; 53 tree[rr] = LL(right - (mid + 1) + 1) * maxt[x]; 54 } 55 if(a <= mid && maxt[ll] > val) update(ll, left, mid, a, b, val); 56 if(mid < b && maxt[rr] > val) update(rr, mid + 1, right, a, b, val); 57 tree[x] = tree[ll] + tree[rr]; 58 maxt[x] = max(maxt[ll], maxt[rr]); 59 mint[x] = min(mint[ll], mint[rr]); 60 } 61 } 62 63 LL solve() { 64 LL ret = 0; 65 build(1, 1, n); 66 for(int i = 0; i <= n && tree[1]; ++i) { 67 int last = 0; 68 for(int p = head[i]; p; p = next[p]) { 69 update(1, 1, n, last + 1, pos[p], n - pos[p] + 1); 70 last = pos[p]; 71 } 72 update(1, 1, n, last + 1, n, 0); 73 ret += tree[1]; 74 } 75 return ret; 76 } 77 78 int main() { 79 while(scanf("%d", &n) != EOF && n) { 80 for(int i = 1; i <= n; ++i) scanf("%d", &a[i]); 81 init(); 82 for(int i = n; i > 0; --i) if(a[i] <= n) add_link(a[i], i); 83 cout<<solve()<<endl; 84 } 85 }