Example

Input

4
1 1 2


Output

6
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,k,n) for(int i = (k); i < (n); i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(a) a.begin(), a.end()
#define MS(m,v) memset(m,v,sizeof(m))
#define D10 fixed<<setprecision(10)
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int, int> pii;
const int MOD = 1000000007;
const int INF = MOD + 1;
const ld EPS = 1e-12;
template<class T> T &chmin(T &a, const T &b) { return a = min(a, b); }
template<class T> T &chmax(T &a, const T &b) { return a = max(a, b); }

/*--------------------template--------------------*/

int V, LOG_V, ROOT;
vector<vi> g;		//bidirectional graph
vector<vi> parent;
vi depth;

void dfs(int v, int p, int d)
{
	parent[0][v] = p;
	depth[v] = d;
	REP(i, g[v].size()) if (g[v][i] != p) dfs(g[v][i], v, d + 1);
}

void init(int root)
{
	ROOT = root;
	V = g.size(); LOG_V = log2(V) + 1;
	parent.resize(LOG_V, vi(V));
	depth.resize(V);
	dfs(ROOT, -1, 0);
	REP(k, LOG_V - 1)REP(v, V)
	{
		if (parent[k][v] < 0) parent[k + 1][v] = -1;
		else parent[k + 1][v] = parent[k][parent[k][v]];
	}
}

int lca(int u, int v)
{
	if (depth[u] > depth[v]) swap(u, v);
	REP(k, LOG_V)
	{
		if (((depth[v] - depth[u]) >> k) & 1) v = parent[k][v];
	}
	if (u == v) return u;
	for (int k = LOG_V - 1; k >= 0; k--)
	{
		if (parent[k][u] != parent[k][v])
		{
			u = parent[k][u];
			v = parent[k][v];
		}
	}
	return parent[0][u];
}

int main()
{
	cin >> V;
	g.resize(V);
	FOR(i, 1, V)
	{
		int t; cin >> t;
		t--;
		g[i].push_back(t);
		g[t].push_back(i);
	}
	init(0);
	vi visit;
	queue<int> que; set<int> st;
	que.push(0);
	visit.push_back(0);
	st.insert(0);
	while (que.size())
	{
		int t = que.front();
		que.pop();
		REP(i, g[t].size())
		{
			int nx = g[t][i];
			if (st.count(nx)) continue;
			st.insert(nx);
			visit.push_back(nx);
			que.push(nx);
		}
	}
	ll ans = 0;
	REP(i, visit.size() - 1)
	{
		int node = lca(visit[i], visit[i + 1]);
		int d = depth[node];
		ans += depth[visit[i]] + depth[visit[i + 1]] - d * 2;
	}
	cout << ans << endl;
	return 0;
}