Example

Input

4
1 1 2


Output

6
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>
#include <set>
using namespace std;
typedef long long ll;
typedef unsigned long long Ull;
#define MM(a,b) memset(a,b,sizeof(a));
const double eps = 1e-10;
const int  inf =0x7f7f7f7f;
const double pi=acos(-1);
const int maxn=100000+10;
int c[maxn][22],deep[maxn],vis[maxn];
vector<vector<int> > G(maxn);

void dfs(int u,int par)
{
    c[u][0]=par;
    for(int i=1;i<=20;i++) c[u][i]=c[c[u][i-1]][i-1];
    for(int i=0;i<G[u].size();i++)
    {
        int v=G[u][i];
        if(v==par) continue;
        deep[v]=deep[u]+1;
        dfs(v,u);
    }
}

int lca(int u,int v)
{
    if(deep[u]<deep[v]) swap(u,v);
    for(int i=20;i>=0;i--)
      if(deep[c[u][i]]>=deep[v])
          u=c[u][i];
    if(u==v) return u;
    for(int i=20;i>=0;i--)
    if(c[u][i]^c[v][i])
    {
        u=c[u][i];
        v=c[v][i];
    }
    return c[u][0];
}

int dis(int u,int v)
{
    /* printf("u:%d deep[u]:%d\n",u,deep[u]);
     printf("v:%d deep[v]:%d\n",v,deep[v]);
     printf("lca:%d deeplca:%d\n",lca(u,v),deep[lca(u,v)]);
     printf("dis:%d\n",deep[u]+deep[v]-2*deep[lca(u,v)]);
     printf("\n");
     */
     return deep[u]+deep[v]-2*deep[lca(u,v)];
}

int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        for(int i=1;i<=n;i++) G[i].clear();
        deep[1]=0;
        for(int i=2;i<=n;i++)
        {
            int x;scanf("%d",&x);
            G[x].push_back(i);
        }
        dfs(1,1);
       // for(int i=1;i<=n;i++)
        //   printf("deep:%d %d\n",i,deep[i]);
       //for(int i=1;i<=n;i++)
        //  for(int j=1;j<=n;j++)
         //    printf("ww%d %d %d\n",i,j,dis(i,j));

        int pre=1;ll ans=0;
        queue<int> q;
        q.push(1);
        while(q.size())
        {
            int u=q.front();q.pop();
            for(int i=0;i<G[u].size();i++)
            {
                 int v=G[u][i];
                 ans+=dis(pre,v);
                 pre=v;
                 q.push(v);
            }
        }
        printf("%lld\n",ans);
    }
    return 0;
}