Example

Input

4
1 1 2


Output

6
#include <bits/stdc++.h>

using namespace std;

#define int long long

struct LCA
{
  vector< vector<int> > tree, parent;
  vector<int> depth;
  int log_V;
  LCA(int V)
  {
    log_V = 1;
    while((1 << log_V) <= V) log_V++;
    tree.resize(V);
    parent.resize(log_V, vector<int>(V, -1));    
    depth.resize(V);
  }
  void add_edge(int u, int v, bool bi = true)
  {
    tree[u].emplace_back(v);
    if(bi) tree[v].emplace_back(u);    
  }
  void dfs(int u, int p, int d)
  {
    parent[0][u] = p;
    depth[u] = d;
    for(auto v : tree[u]) {
      if(v != p) dfs(v, u, d + 1);
    }
  }
  void init(int root = 0)
  {
    dfs(root, -1, 0);
    for(int i = 0; i + 1 < log_V; i++) {
      for(int v = 0; v < parent[i].size(); v++) {
	if(parent[i][v] < 0) parent[i + 1][v] = -1;
	else parent[i + 1][v] = parent[i][parent[i][v]];
      }
    }
  }
  int trace(int u, int v)
  {
    if(depth[u] > depth[v]) swap(u, v);
    for(int i = 0; i < log_V; i++) {
      if((depth[v] - depth[u]) >> i & 1) v = parent[i][v];
    }
    if(u == v) return u;
    for(int i = log_V-1; i >= 0; i--) {
      if(parent[i][u] != parent[i][v]) u = parent[i][u], v = parent[i][v];
    }
    return parent[0][u];
  }
  int dist(int u, int v) {
    return depth[u] + depth[v] - 2*depth[trace(u, v)];
  }
};

signed main()
{
  int n; cin >> n;
  LCA lca(n);
  for(int i = 1; i < n; i++) {
    int p; cin >> p; p--;
    lca.add_edge(p, i, false);
  }
  lca.init();
  int ans = 0, prev = 0;
  queue<int> que; que.push(0);
  while(!que.empty()) {
    int now = que.front(); que.pop();
    ans += lca.dist(prev, now);
    for(int to : lca.tree[now]) que.push(to);
    prev = now;
  }
  cout << ans << endl;
  
  return 0;
}