Example

Input

4
1 1 2


Output

6
#include<bits/stdc++.h>
#define rep(i,n)for(int i=0;i<(n);i++)
using namespace std;

int p[18][100000], v[100000], d[100000];
vector<int>E[100000];
int lca(int u, int v) {
	if (d[u] > d[v])swap(u, v);
	rep(i, 18) {
		if ((d[v] - d[u]) >> i & 1)v = p[i][v];
	}
	if (u == v)return u;
	for (int i = 17; i >= 0; i--) {
		if (p[i][u] != p[i][v]) {
			u = p[i][u]; v = p[i][v];
		}
	}
	return p[0][u];
}
int main() {
	int n; scanf("%d", &n);
	p[0][0] = -1;
	for (int i = 1; i < n; i++) {
		scanf("%d", &p[0][i]); p[0][i]--;
		E[p[0][i]].push_back(i);
	}
	int c = 0;
	queue<int>que;
	memset(d, -1, sizeof(d));
	d[0] = 0; que.push(0);
	while (!que.empty()) {
		int p = que.front(); que.pop();
		v[c++] = p;
		for (int v : E[p]) {
			if (d[v] == -1) {
				d[v] = d[p] + 1; que.push(v);
			}
		}
	}
	for (int i = 1; i < 18; i++) {
		rep(j, n) {
			if (p[i - 1][j] == -1)p[i][j] = -1;
			else p[i][j] = p[i - 1][p[i - 1][j]];
		}
	}
	long long sum = 0;
	rep(i, n - 1) {
		int u = lca(v[i], v[i + 1]);
		sum += d[v[i]] - d[u] + d[v[i + 1]] - d[u];
	}
	printf("%lld\n", sum);
}