###### Codeforces Round #353 (Div. 2) E. Trains and Statistic

Vasya commutes by train every day. There are n train stations in the city, and at the i-th station it's possible to buy only tickets to stations from i + 1 to ai inclusive. No tickets are sold at the last station.

Let ρi, j be the minimum number of tickets one needs to buy in order to get from stations i to station j. As Vasya is fond of different useless statistic he asks you to compute the sum of all values ρi, j among all pairs 1 ≤ i < j ≤ n.

Input

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of stations.

The second line contains n - 1 integer ai (i + 1 ≤ ai ≤ n), the i-th of them means that at the i-th station one may buy tickets to each station from i + 1 to ai inclusive.

Output

Print the sum of ρi, j among all pairs of 1 ≤ i < j ≤ n.

Examples
Input
4
4 4 4

Output
6

Input
5
2 3 5 5

Output
17

Note

In the first sample it's possible to get from any station to any other (with greater index) using only one ticket. The total number of pairs is 6, so the answer is also 6.

Consider the second sample:

• ρ1, 2 = 1
• ρ1, 3 = 2
• ρ1, 4 = 3
• ρ1, 5 = 3
• ρ2, 3 = 1
• ρ2, 4 = 2
• ρ2, 5 = 2
• ρ3, 4 = 1
• ρ3, 5 = 1
• ρ4, 5 = 1

Thus the answer equals 1 + 2 + 3 + 3 + 1 + 2 + 2 + 1 + 1 + 1 = 17.

#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>
#define got(x) (1<<x)
using namespace std;
long long ans,dp[100007];
int n,a[100007],Max[100007][28];
int gotmax(int x,int y)
{
int l = log2(y-x+1);
return a[Max[x][l]] < a[Max[y-got(l)+1][l]] ? Max[y-got(l)+1][l] : Max[x][l];
}
int main()
{
scanf("%d",&n);
for(int i = 1;i < n;i++)
{
scanf("%d",&a[i]);
Max[i][0] = i;
}
for(int i = 1;got(i) < n;i++)
for(int j = 1;j+got(i)-1 < n;j++)
Max[j][i] = a[Max[j][i-1]] < a[Max[j+got(i-1)][i-1]] ? Max[j+got(i-1)][i-1]:Max[j][i-1];
dp[n] = 0;
for(int i = n-1;i;i--)
{
if(a[i] == n)
{
dp[i] = 1ll*(n - i);
ans += dp[i];
continue;
}
int k = gotmax(i+1,a[i]);
dp[i] = dp[k] + 1ll*(n - i - a[i] + k);
ans += dp[i];
}
cout<<ans<<endl;
}

#### Codeforces Round #353 (Div. 2)E. Trains and Statistic

2016-05-18 16:51:38

#### 【解题报告】Codeforces Round #367 (Div. 2)

2016-08-12 21:37:38

#### 解题报告：Codeforces Round #433 (Div. 2) E. Boredom ( 离线处理+树状数组）

2017-09-07 09:56:36

#### Codeforces Round #443 (Div. 2) E. Tournament

2017-11-01 16:14:48

#### 【CodeForces】CodeForces Round #464 (Div. 2) 题解

2018-02-18 11:05:43

#### Codeforces Round #456 (Div. 2): E. Prime Gift（折半枚举）

2018-01-06 15:03:53

#### Codeforces Round #392 (Div. 2)E. Broken Tree

2017-01-20 19:16:32

#### ICM Technex 2018 and Codeforces Round #463 E. Team Work

2018-02-21 11:49:58

#### CF-Educational Codeforces Round 44 (Rated for Div. 2) A~E

2018-05-22 05:02:25

#### Codeforces Round #452 (Div. 2) - E. Segments Removal（链表+优先队列）

2017-12-21 23:05:16

## 不良信息举报

Codeforces Round #353 (Div. 2) E. Trains and Statistic