Example

Input

4
1 1 2


Output

6
#include <bits/stdc++.h>
using namespace std;
typedef long long lli;

const lli MAXN = 100005;
const lli LG_NMAX = 64;

lli N;
lli par[MAXN][LG_NMAX];
vector<lli> child[MAXN];
lli depth[MAXN];

void init() {
  for (lli k = 1; k < LG_NMAX; ++k) {
    for (lli i = 0; i < N; ++i) {
      par[i][k] = par[par[i][k-1]][k-1];
    }
  }
  memset(depth, -1, sizeof(depth));
  depth[0] = 0;
  for (lli i = 1; i < N; ++i) {
    if (depth[i] != -1) continue;
    vector<lli> v(1, i);
    while (depth[par[v.back()][0]] == -1) {
      v.push_back(par[v.back()][0]);
    }
    while (v.size()) {
      depth[v.back()] = depth[par[v.back()][0]] + 1;
      v.pop_back();
    }
  }
}

lli lca(lli a, lli b) {
  if (depth[a] != depth[b]) {
    if (depth[a] > depth[b]) swap(a, b);
    for (lli i = LG_NMAX - 1; i >= 0; --i) {
      if (depth[a] <= depth[par[b][i]]) {
        b = par[b][i];
      }
    }
  }
  if (a == b) return a;
  for (lli i = LG_NMAX - 1; i >= 0; --i) {
    if (par[a][i] != par[b][i]) {
      a = par[a][i];
      b = par[b][i];
    }
  }
  return par[a][0];
}

int main() {
  while (cin >> N) {
    fill(child, child + MAXN, vector<lli>());
    par[0][0] = 0;
    for (lli i = 1; i < N; ++i) {
      cin >> par[i][0];
      par[i][0]--;
      child[par[i][0]].push_back(i);
    }
    for (lli i = 0; i < N; ++i) {
      sort(child[i].begin(), child[i].end());
    }

    init();

    lli res = 0, prev = 0;
    queue<lli> que;
    que.push(0);
    while (que.size()) {
      const lli v = que.front();
      que.pop();
      res += depth[prev] + depth[v] - depth[lca(prev, v)] * 2;
      prev = v;
      for (lli i = 0; i < child[v].size(); ++i) {
        que.push(child[v][i]);
      }
    }
    cout << res << endl;
  }
  return 0;
}