Example

Input

4
1 1 2


Output

6
#include<iostream>
#include<vector>
#include<stack>
#include<algorithm>
#include<queue>
using namespace std;
#define MAX_N 200000
vector<int>X[MAX_N], D[MAX_N], C;
int Depth[MAX_N], a[MAX_N], b[MAX_N], N, Q, A, B, cnt = 1;
stack<long long>S;
inline void dfs(int p) {
	int A = S.top();
	for (int i = 0; i < X[A].size(); i++) {
		if (a[X[A][i]] == -1) { S.push(X[A][i]); a[X[A][i]] = cnt; b[cnt] = X[A][i]; cnt++; dfs(X[A][i]); }
	}
	S.pop();
}
inline long long LCA(int A, int B) {
	int W = min(Depth[A], Depth[B]); A = a[A]; B = a[B];
	int L = 1, R = W, M;
	if (W == 0 || (Depth[b[A]] == 1 && Depth[b[B]] == 1 && A != B)) { return 0; }
	while (true) {
		int M = (L + R) / 2;
		int pos1 = upper_bound(D[M - 1].begin(), D[M - 1].end(), A) - D[M - 1].begin(); pos1--;
		int pos2 = upper_bound(D[M - 1].begin(), D[M - 1].end(), B) - D[M - 1].begin(); pos2--;
		int pos3 = upper_bound(D[M].begin(), D[M].end(), A) - D[M].begin(); pos3--;
		int pos4 = upper_bound(D[M].begin(), D[M].end(), B) - D[M].begin(); pos4--;
		bool p1 = false, p2 = false; if (pos1 == pos2) { p1 = true; }if (pos3 == pos4) { p2 = true; }
		if (p1 == true && p2 == false) {
			return b[D[M - 1][pos1]];
		}
		if (p1 == true && p2 == true) { L = M + 1; }
		if (p1 == false && p2 == false) { R = M; }
		if (p1 == true && p2 == true && M == W) {
			return b[D[M][pos3]];
		}
	}
}
int main() {
	cin >> N; int G = 0;
	for (int i = 1; i < N; i++) {
		cin >> G; X[G - 1].push_back(i);
	}
	for (int i = 0; i < MAX_N; i++) { Depth[i] = 1 << 30; a[i] = -1; }
	Depth[0] = 0; S.push(0); a[0] = 0;
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < X[i].size(); j++) { Depth[X[i][j]] = Depth[i] + 1; }
	}
	int C1 = 0; dfs(0);
	for (int i = 0; i < N; i++) { D[Depth[i]].push_back(a[i]); }
	for (int i = 0; i < N; i++) { sort(D[i].begin(), D[i].end()); }
	vector<pair<int, int>>vec; long long sum = 0; queue<int>Q;
	Q.push(0); vec.push_back(make_pair(0, 0));
	while (!Q.empty()) {
		int to = Q.front(); Q.pop();
		for (int i = 0; i < X[to].size(); i++) {
			vec.push_back(make_pair(Depth[X[to][i]], X[to][i]));
			Q.push(X[to][i]);
		}
	}
	for (int i = 0; i < N - 1; i++) {
		sum += vec[i].first + vec[i + 1].first;
		sum -= Depth[LCA(vec[i].second, vec[i + 1].second)] * 2;
	}
	cout << sum << endl;
	return 0;
}