Example

Input

4
1 1 2


Output

6
#include <bits/stdc++.h>
#define MAX_V 100001
#define MAX_LOG_V 30
using namespace std;
typedef long long ll;
vector<int> G[MAX_V];
int root;
int parent[MAX_LOG_V][MAX_V];
int depth[MAX_V];

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

void init(int V){
  dfs(root,-1,0);

  for(int k=0; k+1<MAX_LOG_V ;k++)
    for(int v=0; v<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);
  
  for(int k=0; k<MAX_LOG_V ;k++)
    if((depth[v]-depth[u])>>k&1)v=parent[k][v];
  
  if(u==v) return u;
  for(int k=MAX_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];
}

ll dis(int a,int b){return depth[a]+depth[b]-2*depth[lca(a,b)];}

ll calc(vector<int>&v){
  vector<int> nv;
  for(int i=0;i<v.size();i++)
    for(int j=0;j<G[v[i]].size();j++)nv.push_back(G[v[i]][j]);
  if(nv.empty())return 0;
  ll res = dis(v.back(),nv[0]);
  v = nv;
  for(int i=0;i<v.size()-1;i++)res+=dis(v[i],v[i+1]);
  return res;
}

int main(){
  int n;
  cin>>n;
  for(int i=1,a;i<n;i++)cin>>a,G[a-1].push_back(i);
  init(n);
  vector<int>v(1);
  ll r=0,ans=0;
  while((r=calc(v)))ans+=r;
  cout<<ans<<endl;
  return 0;
}