Problem:
A - Breadth-First Search by Foxpower
Problem Statement
Fox Ciel went to JAG Kingdom by bicycle, but she forgot a place where she parked her bicycle. So she needs to search it from a bicycle-parking area before returning home.
The parking area is formed as a unweighted rooted tree $T$ with $n$ vertices, numbered $1$ through $n$. Each vertex has a space for parking one or more bicycles. Ciel thought that she parked her bicycle near the vertex $1$, so she decided to search it from there by the breadth-first search. That is, she searches it at the vertices in the increasing order of their distances from the vertex $1$. If multiple vertices have the same distance, she gives priority to the vertices in the order of searching at their parents. If multiple vertices have the same parent, she searches at the vertex with minimum number at first.
Unlike a computer, she can't go to a next vertex by random access. Thus, if she goes to the vertex $j$ after the vertex $i$, she needs to walk the distance between the vertices $i$ and $j$. BFS by fox power perhaps takes a long time, so she asks you to calculate the total moving distance in the worst case starting from the vertex $1$.
Input
The input is formatted as follows.
$n$
$p_2$ $p_3$ $p_4$ $\cdots$ $p_n$
The first line contains an integer $n$ ($1 \le n \le 10^5$), which is the number of vertices on the unweighted rooted tree $T$.
The second line contains $n-1$ integers $p_i$ ($1 \le p_i < i$), which are the parent of the vertex $i$.
The vertex $1$ is a root node, so $p_1$ does not exist.
Output
Print the total moving distance in the worst case in one line.
Sample Input 1
4
1 1 2
Output for the Sample Input 1
6
Sample Input 2
4
1 1 3
Output for the Sample Input 2
4
Sample Input 3
11
1 1 3 3 2 4 1 3 2 9
Output for the Sample Input 3
25

Submitted solutions:

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;

int N;
const int MAX = 100100;
vector<int> G[MAX];
vector<int> d;
vector<vector<int>> dp(30, vector<int>(MAX));

void dist(int v){
	for(auto c:G[v]){
		d[c] = d[v] + 1;
		dist(c);
	}
}

int la(int v, int di){
	int ret = v;
	for(int i = 29; i >= 0; i--){
		if(ret == -1)return -1;
		if(di >> i & 1){
			ret = dp[i][ret];
		}
	}
	return ret;
}

int lca(int v, int u){
	if(d[v] > d[u])swap(v, u);
	//dist[v] <= dist[u]
	u = la(u, d[u]-d[v]);
	if(u == v){
		return u;
	}
	for(int i = 29; i >= 0; i--){
		int nxtv = dp[i][v];
		int nxtu = dp[i][u];
		if(nxtu != nxtv){
			u = nxtu;
			v = nxtv;
		}
	}
	return dp[0][u];
}

int main(){
	cin >> N;
	vector<int> P(N,-1);
	for(int i = 1; i < N; i++){
		cin >> P[i];
		--P[i];
		G[P[i]].push_back(i);
	}
	d.resize(N);
	dist(0);
	for(int i = 0; i < N; i++){
		dp[0][i] = P[i];
	}
	for(int i = 0; i < 29; i++){
		for(int j = 0; j < N; j++){
			if(dp[i][j] == -1)dp[i+1][j] = -1;
			else dp[i+1][j] = dp[i][dp[i][j]];
		}
	}
	vector<int> vec;
	vector<int> seen(N);
	queue<int> q;
	for(int i = 0; i < N; i++)sort(G[i].begin() , G[i].end());
	q.push(0);
	seen[0] = 1;
	while(!q.empty()){
		int v = q.front();
		q.pop();
		vec.push_back(v);
		for(auto c:G[v]){
			if(seen[c])continue;
			seen[c] = 1;
			q.push(c);
		}
	}
	ll ans = 0;
	for(int i = 0; i < N-1; i++){
		ans += d[vec[i]] + d[vec[i+1]] - d[lca(vec[i],vec[i+1])]*2;
	}
	cout << ans << endl;
}
accuracy: 1
time_ms: 30
memory_kb: 25492
final_rank: 8

code_snippet: // (⁠◕⁠ᴗ⁠◕⁠✿⁠)

// #pragma GCC target("avx2")
// #pragma GCC optimize("O3")
// #pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
#define rep(i, n) for (ll i = 0; i < (n); i++)
#define srep(i, s, n) for (ll i = s; i < (n); i++)
#define len(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
using namespace std;
template<typename T> using vc = vector<T>;
template<typename T> using vv = vc<vc<T>>;
template<typename T> using vvv = vv<vc<T>>;
using vi = vc<int>;using vvi = vv<int>; using vvvi = vv<vi>;
using ll = long long;using vl = vc<ll>;using vvl = vv<ll>; using vvvl = vv<vl>;
using ld = long double; using vld = vc<ld>; using vvld = vc<vld>; using vvvld = vc<vvld>;
using uint = unsigned int;
using ull = unsigned long long;
const ld pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
// const ll mod = 1000000007;
const ll mod = 998244353;
inline bool inside(ll y, ll x, ll H, ll W) {return 0 <= (y) and (y) < (H) and 0 <= (x) and (x) < (W); }

#define debug(var)  do{std::cout << #var << " : \n";view(var);}while(0)
template<typename T> void view(T e){cout << e << endl;}
template<typename T> void view(const vc<T>& v){for(const auto& e : v){ cout << " " << e; } cout << endl;}
template<typename T> void view(const vv<T>& vv){ for(const auto& v : vv){ view(v); } }

int main(){
    int N; cin >> N;
    vvi g(N);
    vvi dbring(N, vi(20, 0));
    rep(i, N - 1){
        int p; cin >> p; p--;
        g[p].push_back(i + 1);
        dbring[i + 1][0] = p;
    }
    rep(i, N) sort(all(g[i]));
    rep(k, 19) rep(i, N) dbring[i][k + 1] = dbring[dbring[i][k]][k];
    vi depth(N);
    auto d = [&](int u, int v){
        int ret = depth[u] + depth[v];
        if (depth[u] < depth[v]) swap(u, v);
        int h = depth[u] - depth[v];
        rep(k, 20) if (h >> k & 1) u = dbring[u][k];
        if (u == v){
            ret -= 2 * depth[u];
            return ret;
        }
        for (int k = 19; k >= 0; k--) if (dbring[u][k] != dbring[v][k]){
            u = dbring[u][k];
            v = dbring[v][k];
        }
        ret -= 2 * depth[dbring[u][0]];
        return ret;
    };
    vi way;
    deque<int> q;
    q.push_back(0);
    depth[0] = 0;
    while (!q.empty()){
        auto v = q.front(); q.pop_front();
        way.push_back(v);
        for (auto u : g[v]){
            depth[u] = depth[v] + 1;
            q.push_back(u);
        }
    }
    ll ans = 0;
    rep(i, len(way) - 1) ans += d(way[i], way[i + 1]);
    cout << ans << endl;
}
accuracy: 1
time_ms: 30
memory_kb: 21320
final_rank: 5

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

/**
 * @brief template
 */

template <typename M, typename N, M (*f)(M, M), M (*g)(M, N), M (*m1)()>
struct SegmentTree {
    int sz, n;
    vector<M> data;
    SegmentTree(int _n = 0) : n(_n) {
        sz = 1;
        while (sz < _n)
            sz <<= 1;
        data.assign(2 * sz, m1());
    }
    void run(vector<M> &v) {
        for (int i = 0; i < (int)v.size(); i++)
            data[i + sz] = v[i];
        for (int k = sz - 1; k > 0; k--)
            data[k] = f(data[2 * k], data[2 * k + 1]);
    }
    void set(int k, const M &x) {
        k += sz;
        data[k] = x;
        while (k >>= 1)
            data[k] = f(data[2 * k], data[2 * k + 1]);
    }
    void update(int k, const N &x) {
        k += sz;
        data[k] = g(data[k], x);
        while (k >>= 1)
            data[k] = f(data[2 * k], data[2 * k + 1]);
    }
    M query(int a, int b) {
        M L = m1(), R = m1();
        for (a += sz, b += sz; a < b; a >>= 1, b >>= 1) {
            if (a & 1)
                L = f(L, data[a++]);
            if (b & 1)
                R = f(data[--b], R);
        }
        return f(L, R);
    }
    M operator[](const int &k) const {
        return data[k + sz];
    }
    vector<M> get() {
        return {data.begin() + sz, data.begin() + sz + n};
    }
    template <class F> int max_right(int L, F ch) const {
        int l = sz + L, w = 1;
        M ansL = m1();
        for (; L + w <= sz; l >>= 1, w <<= 1)
            if (l & 1) {
                if (not ch(f(ansL, data[l])))
                    break;
                ansL = f(ansL, data[l++]);
                L += w;
            }
        while (l <<= 1, w >>= 1) {
            if (L + w <= sz && ch(f(ansL, data[l]))) {
                ansL = f(ansL, data[l++]);
                L += w;
            }
        }
        return L;
    }
    template <class F> int min_left(int R, F ch) const {
        int r = sz + R, w = 1;
        M ansR = m1();
        for (; R - w >= 0; r >>= 1, w <<= 1)
            if (r & 1) {
                if (not ch(f(data[r - 1], ansR)))
                    break;
                ansR = f(data[--r], ansR);
                R -= w;
            }
        while (r <<= 1, w >>= 1) {
            if (R - w >= 0 && ch(f(data[r - 1], ansR))) {
                ansR = f(data[--r], ansR);
                R -= w;
            }
        }
        return R;
    }
};

/**
 * @brief Segment Tree
 */

vector<int> Dep;
vector<int> Ind;
vector<int> Par;
vector<vector<int>> Child;

void DFS(int P, int D) {
    Ind[P] = Dep.size();
    Dep.push_back(D);
    for(int NP : Child[P]) {
        DFS(NP,D+1);
        Dep.push_back(D);
    }
}

int f(int A, int B) {return min(A,B);}
int g(int A, int B) {return B;}
int e() {return inf;}

int main() {
    int N;
    cin >> N;
    Ind.resize(N);
    Par.resize(N);
    Par[0] = -1;
    Child.resize(N);
    rep(i,1,N) {
        cin >> Par[i];
        Par[i]--;
        Child[Par[i]].push_back(i);
    }
    DFS(0,0);
    SegmentTree<int,int,f,g,e> Seg(N*2-1);
    Seg.run(Dep);
    queue<int> Q;
    vector<int> BFS;
    Q.push(0);
    while(!Q.empty()) {
        int P = Q.front();
        BFS.push_back(P);
        Q.pop();
        for(int NP : Child[P]) {
            Q.push(NP);
        }
    }
    ll ANS = 0;
    rep(i,0,N-1) {
        int L = Ind[BFS[i]], R = Ind[BFS[i+1]];
        if (L>R) swap(L,R);
        ANS += (Dep[L] + Dep[R] - Seg.query(L,R+1) * 2);
    }
    cout << ANS << endl;
}
accuracy: 1
time_ms: 20
memory_kb: 17480
final_rank: 1

code_snippet: #include <bits/stdc++.h>
using namespace std;

struct Edge {
    int to;
    long long cost;
};

struct LCA {
    int n;
    vector<vector<Edge>> g;
    vector<vector<int>> par;
    vector<int> dep;
    vector<long long> dist;
    int root;
    
    LCA(vector<vector<Edge>> g_, int root_) :
    n(g_.size()), g(g_), par(n, vector<int>(30)), dep(n, -1), dist(n, -1LL), root(root_) {
        build();
    }
    LCA(vector<vector<int>> g_, int root_) :
    n(g_.size()), g(n), par(n, vector<int>(30)), dep(n, -1), dist(n, -1LL), root(root_) {
        for (int v = 0; v < n; v++) {
            for (int nv : g_[v]) {
                g[v].push_back({nv, 1LL});
            }
        }
        build();
    }
    
    void build() {
        queue<int> q;
        dep[root] = 0;
        dist[root] = 0LL;
        q.push(root);
        while (!q.empty()) {
            int v = q.front();
            q.pop();
            for (auto e : g[v]) {
                int nv = e.to;
                long long d = e.cost;
                if (dep[nv] == -1) {
                    dep[nv] = dep[v] + 1;
                    dist[nv] = dist[v] + d;
                    par[nv][0] = v;
                    q.push(nv);
                }
            }
        }
        for (int j = 1; j < 30; j++) {
            for (int i = 0; i < n; i++) {
                par[i][j] = par[par[i][j - 1]][j - 1];
            }
        }
    }
    
    int getlca(int u, int v) {
        if (dep[u] < dep[v]) {
            swap(u, v);
        }
        for (int j = 0; j < 30; j++) {
            if ((dep[u] - dep[v]) & (1 << j)) {
                u = par[u][j];
            }
        }
        if (u == v) {
            return u;
        }
        for (int j = 29; j >= 0; j--) {
            if (par[u][j] != par[v][j]) {
                u = par[u][j];
                v = par[v][j];
            }
        }
        return par[u][0];
    }
    
    int getla(int v, int k) {
        int res = v;
        for (int j = 0; j < 30; j++) {
            if (k & (1 << j)) {
                res = par[res][j];
            }
        }
        return res;
    }
    
    long long getdist(int u, int v) {
        int l = getlca(u, v);
        return dist[u] + dist[v] - 2 * dist[l];
    }
    
    int getpar(int v) {
        return par[v][0];
    }
    
    bool onpath(int u, int v, int w) {
        return getdist(u, w) + getdist(v, w) == getdist(u, v);
    }
};

int main() {
    int n;
    cin >> n;
    vector<vector<Edge>> g(n);
    for (int i = 1; i < n; i++) {
        int p;
        cin >> p;
        p--;
        g[i].push_back({p, 1LL});
        g[p].push_back({i, 1LL});
    }
    vector<int> order;
    queue<int> q;
    vector<bool> visit(n, false);
    q.push(0);
    visit[0] = true;
    order.push_back(0);
    while (!q.empty()) {
        int v = q.front();
        q.pop();
        vector<int> nxt;
        for (auto e : g[v]) {
            int nv = e.to;
            if (visit[nv]) {
                continue;
            }
            nxt.push_back(nv);
        }
        sort(nxt.begin(), nxt.end());
        for (int nv : nxt) {
            visit[nv] = true;
            q.push(nv);
            order.push_back(nv);
        }
    }
    LCA lca(g, 0);
    long long ans = 0;
    for (int i = 0; i < n - 1; i++) {
        int u = order[i], v = order[i + 1];
        ans += lca.getdist(u, v);
    }
    cout << ans << endl;
}
accuracy: 1
time_ms: 60
memory_kb: 41396
final_rank: 16

code_snippet: #include <bits/stdc++.h>
using namespace std;

struct Edge {
    int to;
    long long cost;
};

struct LCA {
    int n;
    vector<vector<Edge>> g;
    vector<vector<int>> par;
    vector<int> dep;
    vector<long long> dist;
    int root;
    
    LCA(vector<vector<Edge>> g_, int root_) :
    n(g_.size()), g(g_), par(n, vector<int>(30)), dep(n, -1), dist(n, -1LL), root(root_) {
        build();
    }
    LCA(vector<vector<int>> g_, int root_) :
    n(g_.size()), g(n), par(n, vector<int>(30)), dep(n, -1), dist(n, -1LL), root(root_) {
        for (int v = 0; v < n; v++) {
            for (int nv : g_[v]) {
                g[v].push_back({nv, 1LL});
            }
        }
        build();
    }
    
    void build() {
        queue<int> q;
        dep[root] = 0;
        dist[root] = 0LL;
        q.push(root);
        while (!q.empty()) {
            int v = q.front();
            q.pop();
            for (auto e : g[v]) {
                int nv = e.to;
                long long d = e.cost;
                if (dep[nv] == -1) {
                    dep[nv] = dep[v] + 1;
                    dist[nv] = dist[v] + d;
                    par[nv][0] = v;
                    q.push(nv);
                }
            }
        }
        for (int j = 1; j < 30; j++) {
            for (int i = 0; i < n; i++) {
                par[i][j] = par[par[i][j - 1]][j - 1];
            }
        }
    }
    
    int getlca(int u, int v) {
        if (dep[u] < dep[v]) {
            swap(u, v);
        }
        for (int j = 0; j < 30; j++) {
            if ((dep[u] - dep[v]) & (1 << j)) {
                u = par[u][j];
            }
        }
        if (u == v) {
            return u;
        }
        for (int j = 29; j >= 0; j--) {
            if (par[u][j] != par[v][j]) {
                u = par[u][j];
                v = par[v][j];
            }
        }
        return par[u][0];
    }
    
    int getla(int v, int k) {
        int res = v;
        for (int j = 0; j < 30; j++) {
            if (k & (1 << j)) {
                res = par[res][j];
            }
        }
        return res;
    }
    
    long long getdist(int u, int v) {
        int l = getlca(u, v);
        return dist[u] + dist[v] - 2 * dist[l];
    }
    
    int getpar(int v) {
        return par[v][0];
    }
    
    bool onpath(int u, int v, int w) {
        return getdist(u, w) + getdist(v, w) == getdist(u, v);
    }
};

int main() {
    int n;
    cin >> n;
    vector<vector<Edge>> g(n);
    for (int i = 1; i < n; i++) {
        int p;
        cin >> p;
        p--;
        g[i].push_back({p, 1LL});
        g[p].push_back({i, 1LL});
    }
    vector<int> order;
    queue<int> q;
    vector<bool> visit(n, false);
    q.push(0);
    visit[0] = true;
    order.push_back(0);
    while (!q.empty()) {
        int v = q.front();
        q.pop();
        vector<int> nxt;
        for (auto e : g[v]) {
            int nv = e.to;
            if (visit[nv]) {
                continue;
            }
            nxt.push_back(nv);
        }
        sort(nxt.begin(), nxt.end());
        for (int nv : nxt) {
            visit[nv] = true;
            q.push(nv);
            order.push_back(nv);
        }
    }
    LCA lca(g, 0);
    long long ans = 0;
    for (int i = 0; i < n - 1; i++) {
        int u = order[i], v = order[i + 1];
        if (lca.dep[u] < lca.dep[v]) {
            swap(u, v);
        }
        int nu = lca.getla(u, lca.dep[u] - lca.dep[v]);
        int l;
        if (nu == v) {
            l = nu;
        } else {
            int left = 0, right = 1000010;
            while (right - left > 1) {
                int mid = (left + right) / 2;
                if (lca.getla(nu, mid) == lca.getla(v, mid)) {
                    right = mid;
                } else {
                    left = mid;
                }
            }
            l = lca.getla(nu, right);
        }
        ans += lca.dist[u] + lca.dist[v] - 2 * lca.dist[l];
    }
    cout << ans << endl;
}
accuracy: 1
time_ms: 180
memory_kb: 41468
final_rank: 18

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

} // namespace macro

using namespace macro;
#line 3 "A.cpp"

template < class T >
struct tree_graph {
    int n;
    struct edge {
        int from, to, id; T cost;
    };
    std::vector<std::vector< edge >> g, g_org;
    tree_graph(int n) : n(n), g(n), g_org(n) {}

    void add_edge(int u, int v, int i = 0, T c = 1) {
        g[u].push_back(edge{u, v, i, c});
        g[v].push_back(edge{v, u, i, c});
        g_org[u].push_back(edge{u, v, i, c});
        g_org[v].push_back(edge{v, u, i, c});
    }

    std::pair< std::pair<int,int>, T > diameter() {
        std::vector< T > dist(n);
        std::function<void(int,int)> dfs = [&](int v, int p) -> void {
            for(auto [to, c] : g[v]) if(to != p) {
                dist[to] = dist[v] + c;
                dfs(to, v);
            }
        };
        dist[0] = 0; dfs(0, -1);
        int u = max_of(dist).key;
        dist[u] = 0; dfs(u, -1);
        auto [v, d] = max_of(dist);
        return {{u, v}, d};
    }

    std::vector<int> path(int u, int v) {
        std::vector<int> parent(n, -1);
        std::function<void(int,int)> dfs = [&](int v, int p) -> void {
            parent[v] = p;
            for(auto e : g[v]) if(e.to != p) dfs(e.to, v);
        };
        dfs(v, -1);
        std::vector<int> res;
        while(u != -1) res.push_back(u), u = parent[u];
        return res;
    }

    int id, root, heavy_light_decomposed;
    std::vector<int> size, depth, down, up, nxt, par, tour;

    void heavy_light_decomposition(int root = 0) {
        id = 0;
        this->root = root;
        size .assign(n, 0);
        depth.assign(n, 0);
        down.assign(n, -1);
        up  .assign(n, -1);
        tour.assign(n, -1);
        nxt.assign(n, root);
        par.assign(n, root);
        dfs_size(root);
        dfs_hld(root);
        heavy_light_decomposed = 1;
    }

    void dfs_size(int v) {
        size[v] = 1;
        for(auto& e : g[v]) {
            if(e.to == par[v]) {
                if(g[v].size() >= 2 and e.to == g[v][0].to) {
                    std::swap(g[v][0], g[v][1]);
                } else continue;
            }
            depth[e.to] = depth[v] + 1;
            par[e.to] = v;
            dfs_size(e.to);
            size[v] += size[e.to];
            if(size[e.to] > size[g[v][0].to]) std::swap(e, g[v][0]);
        }
    }
    void dfs_hld(int v) {
        down[v] = id++;
        tour[down[v]] = v;
        for(auto e : g[v]) if(e.to != par[v]) {
            nxt[e.to] = (e.to == g[v][0].to ? nxt[v] : e.to);
            dfs_hld(e.to);
        }
        up[v] = id;
    }

    std::vector<std::pair<int,int>> ascend(int u, int v) {
        assert(heavy_light_decomposed);
        std::vector<std::pair<int,int>> res;
        while(nxt[u] != nxt[v]) res.push_back({down[u] + 1, down[nxt[u]]}), u = par[nxt[u]];
        if(u != v) res.push_back({down[u] + 1, down[v] + 1});
        return res;
    }
    std::vector<std::pair<int,int>> descend(int u, int v) {
        assert(heavy_light_decomposed);
        if(u == v) return {};
        if(nxt[u] == nxt[v]) return {{down[u] + 1, down[v] + 1}};
        std::vector<std::pair<int,int>> res = descend(u, par[nxt[v]]);
        res.push_back({down[nxt[v]], down[v] + 1});
        return res;
    }
    std::pair<int,int> idx(int v) { 
        assert(heavy_light_decomposed);
        return {down[v], up[v]};
    }

    template < class func >
    void path_query_comm(int u, int v, bool vertex, const func& f) {
        assert(heavy_light_decomposed);
        int x = lca(u, v);
        for(auto [a, b] : ascend(u, x)) {
            std::tie(a, b) = std::minmax({a, b});
            f(a, b);
        }
        if(vertex) f(down[x], down[x] + 1);
        for(auto [a, b] : descend(x, v)) {
            std::tie(a, b) = std::minmax({a, b});
            f(a, b);
        }
    }
    template < class func >
    void path_query(int u, int v, bool vertex, const func& f) {
        assert(heavy_light_decomposed);
        int x = lca(u, v);
        for(auto [a, b] : ascend(u, x)) f(a, b);
        if(vertex) f(down[x], down[x] + 1);
        for(auto [a, b] : descend(x, v)) f(a, b);
    }
    template < class func >
    void subtree_query(int v, bool vertex, const func& f) {
        assert(heavy_light_decomposed);
        f(down[v] + !vertex, up[v]);
    }
    int parent(int v) {
        assert(heavy_light_decomposed);
        return v == root ? -1 : par[v];
    }
    int la(int v, int d) {
        assert(heavy_light_decomposed);
        while(v != -1) {
            int u = nxt[v];
            if(down[v] - d >= down[u]) return tour[down[v] - d];
            d -= down[v] - down[u] + 1;
            v = parent(u);
        }
        return v;
    }
    int lca(int u, int v) {
        assert(heavy_light_decomposed);
        while(nxt[u] != nxt[v]) {
            if(down[u] < down[v]) std::swap(u, v);
            u = par[nxt[u]];
        }
        return depth[u] < depth[v] ? u : v;
    }
    int dist(int u, int v) {
        assert(heavy_light_decomposed);
        return depth[u] + depth[v] - depth[lca(u, v)] * 2;
    }
    int jump(int u, int v, int d) {
        assert(heavy_light_decomposed);
        int x = lca(u, v);
        if(d <= depth[u] - depth[x]) return la(u, d);
        d -= depth[u] - depth[x];
        if(d <= depth[v] - depth[x]) return la(v, depth[v] - depth[x] - d);
        return -1;
    }
    int in_subtree(int r, int v) {
        return down[v] < down[r] and up[r] <= up[v];
    }
};

int main() {
    int n = in();
    tree_graph<int> tree(n);
    vector<vector<int>> g(n);
    for(int i : rep(1, n)) {
        int p = in(); p--;
        tree.add_edge(p, i);
        g[p].push_back(i);
    }
    tree.heavy_light_decomposition();

    queue<int> q;
    q.push(0);
    i64 ans = 0;
    int prev = 0;
    while(!q.empty()) {
        int v = q.front(); q.pop();
        ans += tree.dist(prev, v);
        prev = v;
        sort(g[v]);
        for(int to : g[v]) q.push(to);
    }
    print(ans);
}
accuracy: 1
time_ms: 30
memory_kb: 31568
final_rank: 13

code_snippet: #include <iostream>
#include <queue>
#include <vector>
using namespace std;

int N, P[100009];
int par[100009][22];
int dst[100009];
vector<int> G[100009];

int prevs(int pos, int x) {
	for (int i = 21; i >= 0; i--) {
		if (x >= (1 << i)) { x -= (1 << i); pos = par[pos][i]; }
	}
	return pos;
}

int lca(int u, int v) {
	if (dst[u] > dst[v]) swap(u, v);
	v = prevs(v, dst[v] - dst[u]);
	if (u == v) return u;

	for (int i = 21; i >= 0; i--) {
		if (par[u][i] == par[v][i]) continue;
		u = par[u][i];
		v = par[v][i];
	}
	return par[u][0];
}

int GetDist(int u, int v) {
	int w = lca(u, v);
	return dst[u] + dst[v] - 2 * dst[w];
}

int main() {
	// Step 1. Input
	cin >> N;
	for (int i = 2; i <= N; i++) cin >> P[i];
	for (int i = 2; i <= N; i++) dst[i] = dst[P[i]] + 1;
	for (int i = 2; i <= N; i++) G[P[i]].push_back(i);

	// Step 2. LCA Init
	for (int i = 2; i <= N; i++) par[i][0] = P[i];
	for (int i = 1; i <= 21; i++) {
		for (int j = 1; j <= N; j++) par[j][i] = par[par[j][i - 1]][i - 1];
	}

	// Step 3. Get BFS Order
	vector<int> Order;
	queue<int> Q; Q.push(1);
	while (!Q.empty()) {
		int pos = Q.front(); Q.pop();
		Order.push_back(pos);
		for (int to : G[pos]) Q.push(to);
	}

	// Step 4. Get Answer
	long long Answer = 0;
	for (int i = 0; i < N - 1; i++) Answer += 1LL * GetDist(Order[i], Order[i + 1]);
	cout << Answer << endl;
	return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 18520
final_rank: 4

code_snippet: #line 1 "/home/maspy/compro/library/my_template.hpp"
#include <bits/stdc++.h>

using namespace std;

using ll = long long;
using pi = pair<ll, ll>;
using vi = vector<ll>;
using u32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;

template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vc<T>>;
template <class T>
using vvvc = vector<vvc<T>>;
template <class T>
using vvvvc = vector<vvvc<T>>;
template <class T>
using vvvvvc = vector<vvvvc<T>>;
template <class T>
using pq = priority_queue<T>;
template <class T>
using pqg = priority_queue<T, vector<T>, greater<T>>;

#define vec(type, name, ...) vector<type> name(__VA_ARGS__)
#define vv(type, name, h, ...) \
  vector<vector<type>> name(h, vector<type>(__VA_ARGS__))
#define vvv(type, name, h, w, ...)   \
  vector<vector<vector<type>>> name( \
      h, vector<vector<type>>(w, vector<type>(__VA_ARGS__)))
#define vvvv(type, name, a, b, c, ...)       \
  vector<vector<vector<vector<type>>>> name( \
      a, vector<vector<vector<type>>>(       \
             b, vector<vector<type>>(c, vector<type>(__VA_ARGS__))))

// https://trap.jp/post/1224/
#define FOR1(a) for (ll _ = 0; _ < ll(a); ++_)
#define FOR2(i, a) for (ll i = 0; i < ll(a); ++i)
#define FOR3(i, a, b) for (ll i = a; i < ll(b); ++i)
#define FOR4(i, a, b, c) for (ll i = a; i < ll(b); i += (c))
#define FOR1_R(a) for (ll i = (a)-1; i >= ll(0); --i)
#define FOR2_R(i, a) for (ll i = (a)-1; i >= ll(0); --i)
#define FOR3_R(i, a, b) for (ll i = (b)-1; i >= ll(a); --i)
#define FOR4_R(i, a, b, c) for (ll i = (b)-1; i >= ll(a); i -= (c))
#define overload4(a, b, c, d, e, ...) e
#define FOR(...) overload4(__VA_ARGS__, FOR4, FOR3, FOR2, FOR1)(__VA_ARGS__)
#define FOR_R(...) \
  overload4(__VA_ARGS__, FOR4_R, FOR3_R, FOR2_R, FOR1_R)(__VA_ARGS__)

#define FOR_subset(t, s) for (ll t = s; t >= 0; t = (t == 0 ? -1 : (t - 1) & s))
#define all(x) x.begin(), x.end()
#define len(x) ll(x.size())
#define elif else if

#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second

#define stoi stoll

ll SUM(vector<int> &A) {
  ll sum = 0;
  for (auto &&a: A) sum += a;
  return sum;
}

template <typename T>
T SUM(vector<T> &A) {
  T sum = T(0);
  for (auto &&a: A) sum += a;
  return sum;
}

#define MIN(v) *min_element(all(v))
#define MAX(v) *max_element(all(v))
#define LB(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define UB(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define UNIQUE(x) sort(all(x)), x.erase(unique(all(x)), x.end())

int popcnt(int x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(ll x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 1, 2)
int topbit(int x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(u32 x) { return (x == 0 ? -1 : 31 - __builtin_clz(x)); }
int topbit(ll x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
int topbit(u64 x) { return (x == 0 ? -1 : 63 - __builtin_clzll(x)); }
// (0, 1, 2, 3, 4) -> (-1, 0, 1, 0, 2)
int lowbit(int x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(u32 x) { return (x == 0 ? -1 : __builtin_ctz(x)); }
int lowbit(ll x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }
int lowbit(u64 x) { return (x == 0 ? -1 : __builtin_ctzll(x)); }

template <typename T, typename U>
T ceil(T x, U y) {
  return (x > 0 ? (x + y - 1) / y : x / y);
}

template <typename T, typename U>
T floor(T x, U y) {
  return (x > 0 ? x / y : (x - y + 1) / y);
}

template <typename T, typename U>
pair<T, T> divmod(T x, U y) {
  T q = floor(x, y);
  return {q, x - q * y};
}

ll binary_search(function<bool(ll)> check, ll ok, ll ng) {
  assert(check(ok));
  while (abs(ok - ng) > 1) {
    auto x = (ng + ok) / 2;
    if (check(x))
      ok = x;
    else
      ng = x;
  }
  return ok;
}

template <typename F>
double binary_search_real(F check, double ok, double ng, int iter = 100) {
  FOR(iter) {
    double x = (ok + ng) / 2;
    if (check(x)) {
      ok = x;
    } else {
      ng = x;
    }
  }
  return (ok + ng) / 2;
}

template <class T, class S>
inline bool chmax(T &a, const S &b) {
  return (a < b ? a = b, 1 : 0);
}
template <class T, class S>
inline bool chmin(T &a, const S &b) {
  return (a > b ? a = b, 1 : 0);
}

vi s_to_vi(const string &S, char first_char) {
  vi A(S.size());
  FOR(i, S.size()) { A[i] = S[i] - first_char; }
  return A;
}

template <typename T>
vector<T> cumsum(vector<T> &A, int off = 1) {
  int N = A.size();
  vector<T> B(N + 1);
  FOR(i, N) { B[i + 1] = B[i] + A[i]; }
  if (off == 0) B.erase(B.begin());
  return B;
}

template <typename CNT, typename T>
vc<CNT> bincount(const vc<T> &A, int size) {
  vc<CNT> C(size);
  for (auto &&x: A) { ++C[x]; }
  return C;
}

template <typename T>
vector<int> argsort(const vector<T> &A) {
  // stable
  vector<int> ids(A.size());
  iota(all(ids), 0);
  sort(all(ids),
       [&](int i, int j) { return A[i] < A[j] || (A[i] == A[j] && i < j); });
  return ids;
}

// A[I[0]], A[I[1]], ...
template <typename T>
vc<T> rearrange(const vc<T> &A, const vc<int> &I) {
  int n = len(I);
  vc<T> B(n);
  FOR(i, n) B[i] = A[I[i]];
  return B;
}
#line 1 "/home/maspy/compro/library/other/io.hpp"
// based on yosupo's fastio
#include <unistd.h>

namespace detail {
template <typename T, decltype(&T::is_modint) = &T::is_modint>
std::true_type check_value(int);
template <typename T>
std::false_type check_value(long);
} // namespace detail

template <typename T>
struct is_modint : decltype(detail::check_value<T>(0)) {};
template <typename T>
using is_modint_t = enable_if_t<is_modint<T>::value>;
template <typename T>
using is_not_modint_t = enable_if_t<!is_modint<T>::value>;

struct Scanner {
  FILE *fp;
  char line[(1 << 15) + 1];
  size_t st = 0, ed = 0;
  void reread() {
    memmove(line, line + st, ed - st);
    ed -= st;
    st = 0;
    ed += fread(line + ed, 1, (1 << 15) - ed, fp);
    line[ed] = '\0';
  }
  bool succ() {
    while (true) {
      if (st == ed) {
        reread();
        if (st == ed) return false;
      }
      while (st != ed && isspace(line[st])) st++;
      if (st != ed) break;
    }
    if (ed - st <= 50) {
      bool sep = false;
      for (size_t i = st; i < ed; i++) {
        if (isspace(line[i])) {
          sep = true;
          break;
        }
      }
      if (!sep) reread();
    }
    return true;
  }
  template <class T, enable_if_t<is_same<T, string>::value, int> = 0>
  bool read_single(T &ref) {
    if (!succ()) return false;
    while (true) {
      size_t sz = 0;
      while (st + sz < ed && !isspace(line[st + sz])) sz++;
      ref.append(line + st, sz);
      st += sz;
      if (!sz || st != ed) break;
      reread();
    }
    return true;
  }
  template <class T, enable_if_t<is_integral<T>::value, int> = 0>
  bool read_single(T &ref) {
    if (!succ()) return false;
    bool neg = false;
    if (line[st] == '-') {
      neg = true;
      st++;
    }
    ref = T(0);
    while (isdigit(line[st])) { ref = 10 * ref + (line[st++] & 0xf); }
    if (neg) ref = -ref;
    return true;
  }
  template <class T, is_modint_t<T> * = nullptr>
  bool read_single(T &ref) {
    long long val = 0;
    bool f = read_single(val);
    ref = T(val);
    return f;
  }
  bool read_single(double &ref) {
    string s;
    if (!read_single(s)) return false;
    ref = std::stod(s);
    return true;
  }
  bool read_single(char &ref) {
    string s;
    if (!read_single(s) || s.size() != 1) return false;
    ref = s[0];
    return true;
  }
  template <class T>
  bool read_single(vector<T> &ref) {
    for (auto &d: ref) {
      if (!read_single(d)) return false;
    }
    return true;
  }
  template <class T, class U>
  bool read_single(pair<T, U> &p) {
    return (read_single(p.first) && read_single(p.second));
  }
  template <class A, class B, class C>
  bool read_single(tuple<A, B, C> &p) {
    return (read_single(get<0>(p)) && read_single(get<1>(p))
            && read_single(get<2>(p)));
  }
  template <class A, class B, class C, class D>
  bool read_single(tuple<A, B, C, D> &p) {
    return (read_single(get<0>(p)) && read_single(get<1>(p))
            && read_single(get<2>(p)) && read_single(get<3>(p)));
  }
  void read() {}
  template <class H, class... T>
  void read(H &h, T &... t) {
    bool f = read_single(h);
    assert(f);
    read(t...);
  }
  Scanner(FILE *fp) : fp(fp) {}
};

struct Printer {
  Printer(FILE *_fp) : fp(_fp) {}
  ~Printer() { flush(); }

  static constexpr size_t SIZE = 1 << 15;
  FILE *fp;
  char line[SIZE], small[50];
  size_t pos = 0;
  void flush() {
    fwrite(line, 1, pos, fp);
    pos = 0;
  }
  void write(const char &val) {
    if (pos == SIZE) flush();
    line[pos++] = val;
  }
  template <class T, enable_if_t<is_integral<T>::value, int> = 0>
  void write(T val) {
    if (pos > (1 << 15) - 50) flush();
    if (val == 0) {
      write('0');
      return;
    }
    if (val < 0) {
      write('-');
      val = -val; // todo min
    }
    size_t len = 0;
    while (val) {
      small[len++] = char(0x30 | (val % 10));
      val /= 10;
    }
    for (size_t i = 0; i < len; i++) { line[pos + i] = small[len - 1 - i]; }
    pos += len;
  }
  void write(const string &s) {
    for (char c: s) write(c);
  }
  void write(const char *s) {
    size_t len = strlen(s);
    for (size_t i = 0; i < len; i++) write(s[i]);
  }
  void write(const double &x) {
    ostringstream oss;
    oss << setprecision(15) << x;
    string s = oss.str();
    write(s);
  }
  void write(const long double &x) {
    ostringstream oss;
    oss << setprecision(15) << x;
    string s = oss.str();
    write(s);
  }
  template <class T, is_modint_t<T> * = nullptr>
  void write(T &ref) {
    write(ref.val);
  }
  template <class T>
  void write(const vector<T> &val) {
    auto n = val.size();
    for (size_t i = 0; i < n; i++) {
      if (i) write(' ');
      write(val[i]);
    }
  }
  template <class T, class U>
  void write(const pair<T, U> &val) {
    write(val.first);
    write(' ');
    write(val.second);
  }
  template <class A, class B, class C>
  void write(const tuple<A, B, C> &val) {
    auto &[a, b, c] = val;
    write(a), write(' '), write(b), write(' '), write(c);
  }
  template <class A, class B, class C, class D>
  void write(const tuple<A, B, C, D> &val) {
    auto &[a, b, c, d] = val;
    write(a), write(' '), write(b), write(' '), write(c), write(' '), write(d);
  }
  template <class A, class B, class C, class D, class E>
  void write(const tuple<A, B, C, D, E> &val) {
    auto &[a, b, c, d, e] = val;
    write(a), write(' '), write(b), write(' '), write(c), write(' '), write(d), write(' '), write(e);
  }
  template <class A, class B, class C, class D, class E, class F>
  void write(const tuple<A, B, C, D, E, F> &val) {
    auto &[a, b, c, d, e, f] = val;
    write(a), write(' '), write(b), write(' '), write(c), write(' '), write(d), write(' '), write(e), write(' '), write(f);
  }
  template <class T, size_t S>
  void write(const array<T, S> &val) {
    auto n = val.size();
    for (size_t i = 0; i < n; i++) {
      if (i) write(' ');
      write(val[i]);
    }
  }
  void write(i128 val) {
    string s;
    bool negative = 0;
    if(val < 0){
      negative = 1;
      val = -val;
    }
    while (val) {
      s += '0' + int(val % 10);
      val /= 10;
    }
    if(negative) s += "-";
    reverse(all(s));
    if (len(s) == 0) s = "0";
    write(s);
  }
};

Scanner scanner = Scanner(stdin);
Printer printer = Printer(stdout);

void flush() { printer.flush(); }
void print() { printer.write('\n'); }
template <class Head, class... Tail>
void print(Head &&head, Tail &&... tail) {
  printer.write(head);
  if (sizeof...(Tail)) printer.write(' ');
  print(forward<Tail>(tail)...);
}

void read() {}
template <class Head, class... Tail>
void read(Head &head, Tail &... tail) {
  scanner.read(head);
  read(tail...);
}

#define INT(...)   \
  int __VA_ARGS__; \
  read(__VA_ARGS__)
#define LL(...)   \
  ll __VA_ARGS__; \
  read(__VA_ARGS__)
#define STR(...)      \
  string __VA_ARGS__; \
  read(__VA_ARGS__)
#define CHAR(...)      \
  char __VA_ARGS__; \
  read(__VA_ARGS__)
#define DBL(...)      \
  double __VA_ARGS__; \
  read(__VA_ARGS__)

#define VEC(type, name, size) \
  vector<type> name(size);    \
  read(name)
#define VV(type, name, h, w)                     \
  vector<vector<type>> name(h, vector<type>(w)); \
  read(name)

void YES(bool t = 1) { print(t ? "YES" : "NO"); }
void NO(bool t = 1) { YES(!t); }
void Yes(bool t = 1) { print(t ? "Yes" : "No"); }
void No(bool t = 1) { Yes(!t); }
void yes(bool t = 1) { print(t ? "yes" : "no"); }
void no(bool t = 1) { yes(!t); }
#line 2 "/home/maspy/compro/library/graph/base.hpp"

template <typename T>
struct Edge {
  int frm, to;
  T cost;
  int id;
};

template <typename T = int, bool directed = false>
struct Graph {
  int N, M;
  using cost_type = T;
  using edge_type = Edge<T>;
  vector<edge_type> edges;
  vector<int> indptr;
  vector<edge_type> csr_edges;
  bool prepared;

  class OutgoingEdges {
  public:
    OutgoingEdges(const Graph* G, int l, int r) : G(G), l(l), r(r) {}

    const edge_type* begin() const {
      if (l == r) { return 0; }
      return &G->csr_edges[l];
    }

    const edge_type* end() const {
      if (l == r) { return 0; }
      return &G->csr_edges[r];
    }

  private:
    const Graph* G;
    int l, r;
  };

  bool is_prepared() { return prepared; }
  constexpr bool is_directed() { return directed; }

  Graph() : N(0), M(0), prepared(0) {}
  Graph(int N) : N(N), M(0), prepared(0) {}

  void add(int frm, int to, T cost = 1, int i = -1) {
    assert(!prepared);
    assert(0 <= frm && 0 <= to && to < N);
    if (i == -1) i = M;
    auto e = edge_type({frm, to, cost, i});
    edges.eb(e);
    ++M;
  }

  // wt, off
  void read_tree(bool wt = false, int off = 1) { read_graph(N - 1, wt, off); }

  void read_graph(int M, bool wt = false, int off = 1) {
    for (int m = 0; m < M; ++m) {
      INT(a, b);
      a -= off, b -= off;
      if (!wt) {
        add(a, b);
      } else {
        T c;
        read(c);
        add(a, b, c);
      }
    }
    build();
  }

  void read_parent(int off = 1) {
    for (int v = N - 1; v >= 1; --v) {
      INT(p);
      p -= off;
      add(p, v);
    }
    build();
  }

  void build() {
    assert(!prepared);
    prepared = true;
    indptr.assign(N + 1, 0);
    for (auto&& e: edges) {
      indptr[e.frm + 1]++;
      if (!directed) indptr[e.to + 1]++;
    }
    for (int v = 0; v < N; ++v) { indptr[v + 1] += indptr[v]; }
    auto counter = indptr;
    csr_edges.resize(indptr.back() + 1);
    for (auto&& e: edges) {
      csr_edges[counter[e.frm]++] = e;
      if (!directed)
        csr_edges[counter[e.to]++] = edge_type({e.to, e.frm, e.cost, e.id});
    }
  }

  OutgoingEdges operator[](int v) const {
    assert(prepared);
    return {this, indptr[v], indptr[v + 1]};
  }

  void debug() {
    print("Graph");
    if (!prepared) {
      print("frm to cost id");
      for (auto&& e: edges) print(e.frm, e.to, e.cost, e.id);
    } else {
      print("indptr", indptr);
      print("frm to cost id");
      FOR(v, N) for (auto&& e: (*this)[v]) print(e.frm, e.to, e.cost, e.id);
    }
  }
};
#line 3 "/home/maspy/compro/library/graph/hld.hpp"

/*
HL分解。O(N) 時間構築。
LCA, LA などは O(logN) 時間。
木以外、非連結でも使えるようにした。dfs順序や親がとれる。
*/
template <typename Graph>
struct HLD {
  Graph &G;
  using Graph_type = Graph;
  using WT = typename Graph::cost_type;
  int N;
  vector<int> LID, RID, head, V, parent, root;
  vc<int> depth;
  vc<WT> depth_weighted;
  vector<bool> in_tree;

  HLD(Graph &G, int r = -1)
      : G(G),
        N(G.N),
        LID(G.N),
        RID(G.N),
        head(G.N, r),
        V(G.N),
        parent(G.N, -1),
        root(G.N, -1),
        depth(G.N, -1),
        depth_weighted(G.N, 0),
        in_tree(G.M, 0) {
    assert(G.is_prepared());
    int t1 = 0;
    if (r != -1) {
      dfs_sz(r, -1);
      dfs_hld(r, t1);
    } else {
      for (int r = 0; r < N; ++r) {
        if (parent[r] == -1) {
          head[r] = r;
          dfs_sz(r, -1);
          dfs_hld(r, t1);
        }
      }
    }
    for (auto &&v: V) root[v] = (parent[v] == -1 ? v : root[parent[v]]);
  }

  void dfs_sz(int v, int p) {
    auto &sz = RID;
    parent[v] = p;
    depth[v] = (p == -1 ? 0 : depth[p] + 1);
    sz[v] = 1;
    int l = G.indptr[v], r = G.indptr[v + 1];
    auto &csr = G.csr_edges;
    // 使う辺があれば先頭にする
    for (int i = r - 2; i >= l; --i) {
      if (depth[csr[i + 1].to] == -1) swap(csr[i], csr[i + 1]);
    }
    int hld_sz = 0;
    for (int i = l; i < r; ++i) {
      auto e = csr[i];
      if (depth[e.to] != -1) continue;
      in_tree[e.id] = 1;
      depth_weighted[e.to] = depth_weighted[v] + e.cost;
      dfs_sz(e.to, v);
      sz[v] += sz[e.to];
      if (chmax(hld_sz, sz[e.to]) && l < i) { swap(csr[l], csr[i]); }
    }
  }

  void dfs_hld(int v, int &times) {
    LID[v] = times++;
    RID[v] += LID[v];
    V[LID[v]] = v;
    bool heavy = true;
    for (auto &&e: G[v]) {
      if (!in_tree[e.id] || depth[e.to] <= depth[v]) continue;
      head[e.to] = (heavy ? head[v] : e.to);
      heavy = false;
      dfs_hld(e.to, times);
    }
  }

  int e_to_v(int eid) {
    auto e = G.edges[eid];
    return (parent[e.frm] == e.to ? e.frm : e.to);
  }

  int ELID(int v) { return 2 * LID[v] - depth[v]; }
  int ERID(int v) { return 2 * RID[v] - depth[v] - 1; }

  /* k: 0-indexed */
  int LA(int v, int k) {
    assert(k <= depth[v]);
    while (1) {
      int u = head[v];
      if (LID[v] - k >= LID[u]) return V[LID[v] - k];
      k -= LID[v] - LID[u] + 1;
      v = parent[u];
    }
  }

  int LCA(int u, int v) {
    for (;; v = parent[head[v]]) {
      if (LID[u] > LID[v]) swap(u, v);
      if (head[u] == head[v]) return u;
    }
  }

  int lca(int u, int v) { return LCA(u, v); }
  int la(int u, int v) { return LA(u, v); }

  int subtree_size(int v) { return RID[v] - LID[v]; }

  int dist(int a, int b) {
    int c = LCA(a, b);
    return depth[a] + depth[b] - 2 * depth[c];
  }

  WT dist(int a, int b, bool weighted) {
    assert(weighted);
    int c = LCA(a, b);
    return depth_weighted[a] + depth_weighted[b] - 2 * depth_weighted[c];
  }

  bool in_subtree(int a, int b) { return LID[b] <= LID[a] && LID[a] < RID[b]; }

  int jump(int a, int b, int k = 1) {
    if (k == 1) {
      if (a == b) return -1;
      return (in_subtree(b, a) ? LA(b, depth[b] - depth[a] - 1) : parent[a]);
    }
    int c = LCA(a, b);
    int d_ac = depth[a] - depth[c];
    int d_bc = depth[b] - depth[c];
    if (k > d_ac + d_bc) return -1;
    if (k <= d_ac) return LA(a, k);
    return LA(b, d_ac + d_bc - k);
  }

  vc<int> collect_child(int v) {
    vc<int> res;
    for (auto &&e: G[v])
      if (e.to != parent[v]) res.eb(e.to);
    return res;
  }

  vc<pair<int, int>> get_path_decomposition(int u, int v, bool edge) {
    // [始点, 終点] の"閉"区間列。
    vc<pair<int, int>> up, down;
    while (1) {
      if (head[u] == head[v]) break;
      if (LID[u] < LID[v]) {
        down.eb(LID[head[v]], LID[v]);
        v = parent[head[v]];
      } else {
        up.eb(LID[u], LID[head[u]]);
        u = parent[head[u]];
      }
    }
    if (LID[u] < LID[v]) down.eb(LID[u] + edge, LID[v]);
    elif (LID[v] + edge <= LID[u]) up.eb(LID[u], LID[v] + edge);
    reverse(all(down));
    up.insert(up.end(), all(down));
    return up;
  }

  void debug() {
    print("V", V);
    print("LID", LID);
    print("RID", RID);
    print("parent", parent);
    print("depth", depth);
    print("head", head);
    print("in_tree(edge)", in_tree);
    print("root", root);
  }
};
#line 4 "main.cpp"

void solve() {
  LL(N);
  Graph<int, 1> G(N);
  FOR(v, 1, N) {
    LL(p);
    --p;
    G.add(p, v);
  }
  G.build();

  int p = 0;
  vc<int> V;
  auto add = [&](int v) -> void { V.eb(v); };
  add(0);
  while (p < len(V)) {
    int v = V[p++];
    vc<int> TO;
    for (auto&& e: G[v]) TO.eb(e.to);
    sort(all(TO));
    for (auto&& x: TO) add(x);
  }
  HLD<decltype(G)> hld(G);
  ll ANS = 0;
  FOR(i, len(V) - 1) {
    int a = V[i], b = V[i + 1];
    ANS += hld.dist(a, b);
  }
  print(ANS);
}

signed main() {
  cout << fixed << setprecision(15);

  ll T = 1;
  // LL(T);
  FOR(T) solve();

  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 19660
final_rank: 2

code_snippet: #pragma GCC target( "sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
 
#include<bits/stdc++.h>	
 
using namespace std;
 
#define all(a) a.begin(), a.end()                                                   
#define rall(a) a.rbegin(), a.rend()
#define sz(a) a.size()
#define pb push_back
#define vt vector
#define s second
#define f first
#define nl '\n'
 
using ll = long long;
using pii = pair<int, int>;
 
vt<pii> dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
 
const int N = 5e5 + 5, mod = 1e9 + 7;

const int inf = 2e9;
 
double eps = 1e-6;
 
bool fl = 0;

vt<int> g[N];

int up[N][18];

int tin[N], tout[N], timer;

void calc(int u, int p) {
	tin[u] = timer++;
	up[u][0] = p;
	for (int i = 1; i < 18; i++) {
	 	up[u][i] = up[up[u][i - 1]][i - 1];
	}
	for (int to: g[u]) {
		calc(to, u);
	}
	tout[u] = timer++;
}

bool is(int u, int v) {
	return tin[u] <= tin[v] && tout[u] >= tout[v];
}

int lca(int u, int v) {
	if (is(u, v)) return u;
	if (is(v, u)) return v;
	for (int i = 17; i >= 0; i--) {
		int x = up[u][i];
		if (is(x, v)) continue;
		u = x;
	}
	return up[u][0];
}

int gt(int u, int lc) {
	if (u == lc) return 0;
	int ans = 0;
	for (int i = 17; i >= 0; i--) {
		int v = up[u][i];
		if (is(v, lc)) continue;
		ans += (1 << i);
		u = v;
	}
	return ans + 1;
}

int get(int u, int v) {
	int lc = lca(u, v);
	return gt(u, lc) + gt(v, lc);
}

void slv() {
	int n;
	cin >> n;
	for (int i = 2; i <= n; i++) {
		int p;
		cin >> p;
		g[p].pb(i);
	}
	calc(1, 1);
	vt<pii> s;
	queue<int> q;
	vt<int> d(n + 1);
	d[1] = 0;
	q.push(1);
	int cnt = 1;
	while (!q.empty()) {
		int u = q.front();
		q.pop();
		s.pb({cnt++, u});
		for (int to: g[u]) {
			if (!d[to]) {
				d[to] = d[u] + 1;
				q.push(to);
			}
		}
	}
	sort(all(s));
	int ans = 0;
	for (int i = 1; i < n; i++) {
		ans += get(s[i - 1].s, s[i].s);
	}
	cout << ans << nl;
}           
 
int main() {                                                         
	//freopen("input.txt", "r", stdin);                                                                                     
	//freopen("output.txt", "w", stdout);                                                                                     
	ios_base::sync_with_stdio(NULL);                                                                                       
	cin.tie(NULL);
	int tp = 1;
	if (fl) cin >> tp;
	while (tp--) {
		slv();
	}
}
accuracy: 0.5901639344262295
time_ms: 20
memory_kb: 34108
final_rank: 20

code_snippet: #include<vector>
#include<queue>
#include<iostream>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define Int long long

using Graph = vector<vector<int>>;

struct LCA{
  vector<vector<int>> parent;
  vector<int> dist;
  LCA(const Graph &G, int root=0){ init(G, root);}

  void init(const Graph &G, int root=0){
    int V = G.size();
    int K = 1;
    while((1<<K) < V) K++;
    parent.assign(K, vector<int>(V, -1));
    dist.assign(V, -1);
    dfs(G, root, -1, 0);
    for(int k=0; k+1<K;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]];
        }
      }
    }
  }

  // 根からの距離とひとつ先の頂点を求める
  void dfs(const Graph &G, int v, int p, int d){
    parent[0][v] = p;
    dist[v] = d;
    for(auto nx : G[v]){
      if(nx != p) dfs(G, nx, v, d+1);
    }
  }

  int query(int u, int v){
    if(dist[u] < dist[v]) swap(u, v);
    int K = parent.size();
    for(int k=0; k<K;k++){
      if((dist[u] - dist[v]) >> k & 1){
        u = parent[k][u];
      }
    }
    if(u == v) return u;
    for(int k=K-1;k>=0; k--){
      if(parent[k][u] != parent[k][v]){
        u = parent[k][u];
        v = parent[k][v];
      }
    }
    return parent[0][u];
  }

  int get_dist(int u, int v){
    int p = query(u, v);
    return dist[u] + dist[v] - 2 * dist[p];
  }
};

queue<int> bfs(const Graph &G, int root=0){
  vector<bool> check(G.size(), false);
  queue<int> que, order;
  check[root] =  true;
  que.push(root);
  order.push(root);
  while(!que.empty()){
    int v = que.front(); que.pop();

    for(int nv: G[v]){
      // 辞書順にしたい
      if(check[nv]) continue;
      que.push(nv);
      order.push(nv);
      check[nv] = true;
    }
  }
  return order;
}

int main(){
  int N, x;
  cin >> N;
  Graph G(N);
  for(int i=1;i<N;i++){
    cin >> x;
    x--;
    G[i].push_back(x);
    G[x].push_back(i);
  }
  LCA lca = LCA(G);
  queue<int> order = bfs(G);

  Int ans = 0;
  int v = order.front();
  order.pop();
  while(!order.empty()){
    int nv = order.front();
    order.pop();
    ans += lca.get_dist(v, nv);
    v = nv;
  }
  cout << ans << endl;
}
accuracy: 1
time_ms: 30
memory_kb: 23580
final_rank: 7

code_snippet: #include <bits/stdc++.h>

#ifdef _MSC_VER
#  include <intrin.h>
#else
#  include <x86intrin.h>
#endif

#include <limits>
#include <type_traits>

namespace suisen {
// ! utility
template <typename ...Types>
using constraints_t = std::enable_if_t<std::conjunction_v<Types...>, std::nullptr_t>;
template <bool cond_v, typename Then, typename OrElse>
constexpr decltype(auto) constexpr_if(Then&& then, OrElse&& or_else) {
    if constexpr (cond_v) {
        return std::forward<Then>(then);
    } else {
        return std::forward<OrElse>(or_else);
    }
}

// ! function
template <typename ReturnType, typename Callable, typename ...Args>
using is_same_as_invoke_result = std::is_same<std::invoke_result_t<Callable, Args...>, ReturnType>;
template <typename F, typename T>
using is_uni_op = is_same_as_invoke_result<T, F, T>;
template <typename F, typename T>
using is_bin_op = is_same_as_invoke_result<T, F, T, T>;

template <typename Comparator, typename T>
using is_comparator = std::is_same<std::invoke_result_t<Comparator, T, T>, bool>;

// ! integral
template <typename T, typename = constraints_t<std::is_integral<T>>>
constexpr int bit_num = std::numeric_limits<std::make_unsigned_t<T>>::digits;
template <typename T, unsigned int n>
struct is_nbit { static constexpr bool value = bit_num<T> == n; };
template <typename T, unsigned int n>
static constexpr bool is_nbit_v = is_nbit<T, n>::value;

// ?
template <typename T>
struct safely_multipliable {};
template <>
struct safely_multipliable<int> { using type = long long; };
template <>
struct safely_multipliable<long long> { using type = __int128_t; };
template <>
struct safely_multipliable<unsigned int> { using type = unsigned long long; };
template <>
struct safely_multipliable<unsigned long int> { using type = __uint128_t; };
template <>
struct safely_multipliable<unsigned long long> { using type = __uint128_t; };
template <>
struct safely_multipliable<float> { using type = float; };
template <>
struct safely_multipliable<double> { using type = double; };
template <>
struct safely_multipliable<long double> { using type = long double; };
template <typename T>
using safely_multipliable_t = typename safely_multipliable<T>::type;

template <typename T, typename = void>
struct rec_value_type {
    using type = T;
};
template <typename T>
struct rec_value_type<T, std::void_t<typename T::value_type>> {
    using type = typename rec_value_type<typename T::value_type>::type;
};
template <typename T>
using rec_value_type_t = typename rec_value_type<T>::type;

} // namespace suisen

// ! type aliases
using i128 = __int128_t;
using u128 = __uint128_t;

template <typename T>
using pq_greater = std::priority_queue<T, std::vector<T>, std::greater<T>>;
template <typename T, typename U>
using umap = std::unordered_map<T, U>;

// ! macros (capital: internal macro)
#define OVERLOAD2(_1,_2,name,...) name
#define OVERLOAD3(_1,_2,_3,name,...) name
#define OVERLOAD4(_1,_2,_3,_4,name,...) name

#define REP4(i,l,r,s)  for(std::remove_reference_t<std::remove_const_t<decltype(r)>>i=(l);i<(r);i+=(s))
#define REP3(i,l,r)    REP4(i,l,r,1)
#define REP2(i,n)      REP3(i,0,n)
#define REPINF3(i,l,s) for(std::remove_reference_t<std::remove_const_t<decltype(l)>>i=(l);;i+=(s))
#define REPINF2(i,l)   REPINF3(i,l,1)
#define REPINF1(i)     REPINF2(i,0)
#define RREP4(i,l,r,s) for(std::remove_reference_t<std::remove_const_t<decltype(r)>>i=(l)+fld((r)-(l)-1,s)*(s);i>=(l);i-=(s))
#define RREP3(i,l,r)   RREP4(i,l,r,1)
#define RREP2(i,n)     RREP3(i,0,n)

#define rep(...)    OVERLOAD4(__VA_ARGS__, REP4   , REP3   , REP2   )(__VA_ARGS__)
#define rrep(...)   OVERLOAD4(__VA_ARGS__, RREP4  , RREP3  , RREP2  )(__VA_ARGS__)
#define repinf(...) OVERLOAD3(__VA_ARGS__, REPINF3, REPINF2, REPINF1)(__VA_ARGS__)

#define CAT_I(a, b) a##b
#define CAT(a, b) CAT_I(a, b)
#define UNIQVAR(tag) CAT(tag, __LINE__)
#define loop(n) for (std::remove_reference_t<std::remove_const_t<decltype(n)>> UNIQVAR(loop_variable) = n; UNIQVAR(loop_variable) --> 0;)

#define all(iterable) std::begin(iterable), std::end(iterable)
#define input(type, ...) type __VA_ARGS__; read(__VA_ARGS__)

#ifdef LOCAL
#  define debug(...) debug_internal(#__VA_ARGS__, __VA_ARGS__)

template <class T, class... Args>
void debug_internal(const char* s, T&& first, Args&&... args) {
    constexpr const char* prefix = "[\033[32mDEBUG\033[m] ";
    constexpr const char* open_brakets = sizeof...(args) == 0 ? "" : "(";
    constexpr const char* close_brakets = sizeof...(args) == 0 ? "" : ")";
    std::cerr << prefix << open_brakets << s << close_brakets << ": " << open_brakets << std::forward<T>(first);
    ((std::cerr << ", " << std::forward<Args>(args)), ...);
    std::cerr << close_brakets << "\n";
}

#else
#  define debug(...) void(0)
#endif

// ! I/O utilities

// __int128_t
std::ostream& operator<<(std::ostream& dest, __int128_t value) {
    std::ostream::sentry s(dest);
    if (s) {
        __uint128_t tmp = value < 0 ? -value : value;
        char buffer[128];
        char* d = std::end(buffer);
        do {
            --d;
            *d = "0123456789"[tmp % 10];
            tmp /= 10;
        } while (tmp != 0);
        if (value < 0) {
            --d;
            *d = '-';
        }
        int len = std::end(buffer) - d;
        if (dest.rdbuf()->sputn(d, len) != len) {
            dest.setstate(std::ios_base::badbit);
        }
    }
    return dest;
}
// __uint128_t
std::ostream& operator<<(std::ostream& dest, __uint128_t value) {
    std::ostream::sentry s(dest);
    if (s) {
        char buffer[128];
        char* d = std::end(buffer);
        do {
            --d;
            *d = "0123456789"[value % 10];
            value /= 10;
        } while (value != 0);
        int len = std::end(buffer) - d;
        if (dest.rdbuf()->sputn(d, len) != len) {
            dest.setstate(std::ios_base::badbit);
        }
    }
    return dest;
}

// pair
template <typename T, typename U>
std::ostream& operator<<(std::ostream& out, const std::pair<T, U>& a) {
    return out << a.first << ' ' << a.second;
}
// tuple
template <unsigned int N = 0, typename ...Args>
std::ostream& operator<<(std::ostream& out, const std::tuple<Args...>& a) {
    if constexpr (N >= std::tuple_size_v<std::tuple<Args...>>) {
        return out;
    } else {
        out << std::get<N>(a);
        if constexpr (N + 1 < std::tuple_size_v<std::tuple<Args...>>) {
            out << ' ';
        }
        return operator<<<N + 1>(out, a);
    }
}
// vector
template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& a) {
    for (auto it = a.begin(); it != a.end();) {
        out << *it;
        if (++it != a.end()) out << ' ';
    }
    return out;
}
// array
template <typename T, size_t N>
std::ostream& operator<<(std::ostream& out, const std::array<T, N>& a) {
    for (auto it = a.begin(); it != a.end();) {
        out << *it;
        if (++it != a.end()) out << ' ';
    }
    return out;
}
inline void print() { std::cout << '\n'; }
template <typename Head, typename... Tail>
inline void print(const Head& head, const Tail &...tails) {
    std::cout << head;
    if (sizeof...(tails)) std::cout << ' ';
    print(tails...);
}
template <typename Iterable>
auto print_all(const Iterable& v, std::string sep = " ", std::string end = "\n") -> decltype(std::cout << *v.begin(), void()) {
    for (auto it = v.begin(); it != v.end();) {
        std::cout << *it;
        if (++it != v.end()) std::cout << sep;
    }
    std::cout << end;
}

__int128_t parse_i128(std::string& s) {
    __int128_t ret = 0;
    for (int i = 0; i < int(s.size()); i++) if ('0' <= s[i] and s[i] <= '9') ret = 10 * ret + s[i] - '0';
    if (s[0] == '-') ret = -ret;
    return ret;
}
__uint128_t parse_u128(std::string& s) {
    __uint128_t ret = 0;
    for (int i = 0; i < int(s.size()); i++) if ('0' <= s[i] and s[i] <= '9') ret = 10 * ret + s[i] - '0';
    return ret;
}
// __int128_t
std::istream& operator>>(std::istream& in, __int128_t& v) {
    std::string s;
    in >> s;
    v = parse_i128(s);
    return in;
}
// __uint128_t
std::istream& operator>>(std::istream& in, __uint128_t& v) {
    std::string s;
    in >> s;
    v = parse_u128(s);
    return in;
}
// pair
template <typename T, typename U>
std::istream& operator>>(std::istream& in, std::pair<T, U>& a) {
    return in >> a.first >> a.second;
}
// tuple
template <unsigned int N = 0, typename ...Args>
std::istream& operator>>(std::istream& in, std::tuple<Args...>& a) {
    if constexpr (N >= std::tuple_size_v<std::tuple<Args...>>) {
        return in;
    } else {
        return operator>><N + 1>(in >> std::get<N>(a), a);
    }
}
// vector
template <typename T>
std::istream& operator>>(std::istream& in, std::vector<T>& a) {
    for (auto it = a.begin(); it != a.end(); ++it) in >> *it;
    return in;
}
// array
template <typename T, size_t N>
std::istream& operator>>(std::istream& in, std::array<T, N>& a) {
    for (auto it = a.begin(); it != a.end(); ++it) in >> *it;
    return in;
}
template <typename ...Args>
void read(Args &...args) {
    (std::cin >> ... >> args);
}

// ! integral utilities

// Returns pow(-1, n)
template <typename T>
constexpr inline int pow_m1(T n) {
    return -(n & 1) | 1;
}
// Returns pow(-1, n)
template <>
constexpr inline int pow_m1<bool>(bool n) {
    return -int(n) | 1;
}

// Returns floor(x / y)
template <typename T>
constexpr inline T fld(const T x, const T y) {
    return (x ^ y) >= 0 ? x / y : (x - (y + pow_m1(y >= 0))) / y;
}
template <typename T>
constexpr inline T cld(const T x, const T y) {
    return (x ^ y) <= 0 ? x / y : (x + (y + pow_m1(y >= 0))) / y;
}

template <typename T, suisen::constraints_t<suisen::is_nbit<T, 16>> = nullptr>
__attribute__((target("popcnt"))) constexpr inline int popcount(const T x) { return _mm_popcnt_u32(x); }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 32>> = nullptr>
__attribute__((target("popcnt"))) constexpr inline int popcount(const T x) { return _mm_popcnt_u32(x); }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 64>> = nullptr>
__attribute__((target("popcnt"))) constexpr inline int popcount(const T x) { return _mm_popcnt_u64(x); }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 16>> = nullptr>
constexpr inline int count_lz(const T x) { return x ? __builtin_clz(x) : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 32>> = nullptr>
constexpr inline int count_lz(const T x) { return x ? __builtin_clz(x) : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 64>> = nullptr>
constexpr inline int count_lz(const T x) { return x ? __builtin_clzll(x) : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 16>> = nullptr>
constexpr inline int count_tz(const T x) { return x ? __builtin_ctz(x) : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 32>> = nullptr>
constexpr inline int count_tz(const T x) { return x ? __builtin_ctz(x) : suisen::bit_num<T>; }
template <typename T, suisen::constraints_t<suisen::is_nbit<T, 64>> = nullptr>
constexpr inline int count_tz(const T x) { return x ? __builtin_ctzll(x) : suisen::bit_num<T>; }
template <typename T>
constexpr inline int floor_log2(const T x) { return suisen::bit_num<T> -1 - count_lz(x); }
template <typename T>
constexpr inline int ceil_log2(const T x) { return floor_log2(x) + ((x & -x) != x); }
template <typename T>
constexpr inline int kth_bit(const T x, const unsigned int k) { return (x >> k) & 1; }
template <typename T>
constexpr inline int parity(const T x) { return popcount(x) & 1; }

// ! container

template <typename T, typename Comparator, suisen::constraints_t<suisen::is_comparator<Comparator, T>> = nullptr>
auto priqueue_comp(const Comparator comparator) {
    return std::priority_queue<T, std::vector<T>, Comparator>(comparator);
}

template <typename Iterable>
auto isize(const Iterable& iterable) -> decltype(int(iterable.size())) {
    return iterable.size();
}

template <typename T, typename Gen, suisen::constraints_t<suisen::is_same_as_invoke_result<T, Gen, int>> = nullptr>
auto generate_vector(int n, Gen generator) {
    std::vector<T> v(n);
    for (int i = 0; i < n; ++i) v[i] = generator(i);
    return v;
}
template <typename T>
auto generate_range_vector(T l, T r) {
    return generate_vector(r - l, [l](int i) { return l + i; });
}
template <typename T>
auto generate_range_vector(T n) {
    return generate_range_vector(0, n);
}

template <typename T>
void sort_unique_erase(std::vector<T>& a) {
    std::sort(a.begin(), a.end());
    a.erase(std::unique(a.begin(), a.end()), a.end());
}

template <typename InputIterator, typename BiConsumer>
auto foreach_adjacent_values(InputIterator first, InputIterator last, BiConsumer f) -> decltype(f(*first++, *last), void()) {
    if (first != last) for (auto itr = first, itl = itr++; itr != last; itl = itr++) f(*itl, *itr);
}
template <typename Container, typename BiConsumer>
auto foreach_adjacent_values(Container c, BiConsumer f) -> decltype(c.begin(), c.end(), void()) {
    foreach_adjacent_values(c.begin(), c.end(), f);
}

// ! other utilities

// x <- min(x, y). returns true iff `x` has chenged.
template <typename T>
inline bool chmin(T& x, const T& y) {
    if (y >= x) return false;
    x = y;
    return true;
}
// x <- max(x, y). returns true iff `x` has chenged.
template <typename T>
inline bool chmax(T& x, const T& y) {
    if (y <= x) return false;
    x = y;
    return true;
}

template <typename T, std::enable_if_t<std::is_integral_v<T>, std::nullptr_t> = nullptr>
std::string bin(T val, int bit_num = -1) {
    std::string res;
    if (bit_num >= 0) {
        for (int bit = bit_num; bit-- > 0;) res += '0' + ((val >> bit) & 1);
    } else {
        for (; val; val >>= 1) res += '0' + (val & 1);
        std::reverse(res.begin(), res.end());
    }
    return res;
}

template <typename T, std::enable_if_t<std::is_integral_v<T>, std::nullptr_t> = nullptr>
std::vector<T> digits_low_to_high(T val, T base = 10) {
    std::vector<T> res;
    for (; val; val /= base) res.push_back(val % base);
    if (res.empty()) res.push_back(T{ 0 });
    return res;
}
template <typename T, std::enable_if_t<std::is_integral_v<T>, std::nullptr_t> = nullptr>
std::vector<T> digits_high_to_low(T val, T base = 10) {
    auto res = digits_low_to_high(val, base);
    std::reverse(res.begin(), res.end());
    return res;
}

template <typename T>
std::string join(const std::vector<T>& v, const std::string& sep, const std::string& end) {
    std::ostringstream ss;
    for (auto it = v.begin(); it != v.end();) {
        ss << *it;
        if (++it != v.end()) ss << sep;
    }
    ss << end;
    return ss.str();
}

namespace suisen {}
using namespace suisen;
using namespace std;

struct io_setup {
    io_setup(int precision = 20) {
        std::ios::sync_with_stdio(false);
        std::cin.tie(nullptr);
        std::cout << std::fixed << std::setprecision(precision);
    }
} io_setup_ {};

// ! code from here

#include <vector>

namespace suisen {
class HeavyLightDecomposition {
    public:
        template <typename Q>
        using is_point_update_query = std::is_invocable<Q, int>;
        template <typename Q>
        using is_range_update_query = std::is_invocable<Q, int, int>;
        template <typename Q, typename T>
        using is_point_get_query  = std::is_same<std::invoke_result_t<Q, int>, T>;
        template <typename Q, typename T>
        using is_range_fold_query = std::is_same<std::invoke_result_t<Q, int, int>, T>;

        using Graph = std::vector<std::vector<int>>;

        HeavyLightDecomposition() = default;
        HeavyLightDecomposition(Graph &g) : n(g.size()), visit(n), leave(n), head(n), ord(n), siz(n), par(n, -1), dep(n, 0) {
            for (int i = 0; i < n; ++i) if (par[i] < 0) dfs(g, i, -1);
            int time = 0;
            for (int i = 0; i < n; ++i) if (par[i] < 0) hld(g, i, -1, time);
        }
        int size() const {
            return n;
        }
        int lca(int u, int v) const {
            for (;; v = par[head[v]]) {
                if (visit[u] > visit[v]) std::swap(u, v);
                if (head[u] == head[v]) return u;
            }
        }
        int la(int u, int k, int default_value = -1) const {
            if (k < 0) return default_value;
            while (u >= 0) {
                int h = head[u];
                if (visit[u] - k >= visit[h]) return ord[visit[u] - k];
                k -= visit[u] - visit[h] + 1;
                u = par[h];
            }
            return default_value;
        }
        int move_to(int u, int v, int d, int default_value = -1) const {
            if (d < 0) return default_value;
            const int w = lca(u, v);
            int uw = dep[u] - dep[w];
            if (d <= uw) return la(u, d);
            int vw = dep[v] - dep[w];
            return d <= uw + vw ? la(v, (uw + vw) - d) : default_value;
        }
        int dist(int u, int v) const {
            return dep[u] + dep[v] - 2 * dep[lca(u, v)];
        }
        template <typename T, typename Q, typename F, constraints_t<is_range_fold_query<Q, T>, is_bin_op<F, T>> = nullptr>
        T fold_path(int u, int v, T identity, F bin_op, Q fold_query, bool is_edge_query = false) const {
            T res = identity;
            for (;; v = par[head[v]]) {
                if (visit[u] > visit[v]) std::swap(u, v);
                if (head[u] == head[v]) break;
                res = bin_op(fold_query(visit[head[v]], visit[v] + 1), res);
            }
            return bin_op(fold_query(visit[u] + is_edge_query, visit[v] + 1), res);
        }
        template <
            typename T, typename Q1, typename Q2, typename F,
            constraints_t<is_range_fold_query<Q1, T>, is_range_fold_query<Q2, T>, is_bin_op<F, T>> = nullptr
        >
        T fold_path_noncommutative(int u, int v, T identity, F bin_op, Q1 fold_query, Q2 fold_query_rev, bool is_edge_query = false) const {
            T res_u = identity, res_v = identity;
            // a := lca(u, v)
            // res = fold(u -> a) + fold(a -> v)
            while (head[u] != head[v]) {
                if (visit[u] < visit[v]) { // a -> v
                    res_v = bin_op(fold_query(visit[head[v]], visit[v] + 1), res_v);
                    v = par[head[v]];
                } else { // u -> a
                    res_u = bin_op(res_u, fold_query_rev(visit[head[u]], visit[u] + 1));
                    u = par[head[u]];
                }
            }
            if (visit[u] < visit[v]) { // a = u
                res_v = bin_op(fold_query(visit[u] + is_edge_query, visit[v] + 1), res_v);
            } else { // a = v
                res_u = bin_op(res_u, fold_query_rev(visit[v] + is_edge_query, visit[u] + 1));
            }
            return bin_op(res_u, res_v);
        }
        template <typename Q, constraints_t<is_range_update_query<Q>> = nullptr>
        void update_path(int u, int v, Q update_query, bool is_edge_query = false) const {
            for (;; v = par[head[v]]) {
                if (visit[u] > visit[v]) std::swap(u, v);
                if (head[u] == head[v]) break;
                update_query(visit[head[v]], visit[v] + 1);
            }
            update_query(visit[u] + is_edge_query, visit[v] + 1);
        }
        template <typename T, typename Q, constraints_t<is_range_fold_query<Q, T>> = nullptr>
        T fold_subtree(int u, Q fold_query, bool is_edge_query = false) const {
            return fold_query(visit[u] + is_edge_query, leave[u]);
        }
        template <typename Q, constraints_t<is_range_update_query<Q>> = nullptr>
        void update_subtree(int u, Q update_query, bool is_edge_query = false) const {
            update_query(visit[u] + is_edge_query, leave[u]);
        }
        template <typename T, typename Q, constraints_t<is_point_get_query<Q, T>> = nullptr>
        T get_point(int u, Q get_query) const {
            return get_query(visit[u]);
        }
        template <typename Q, constraints_t<is_point_update_query<Q>> = nullptr>
        void update_point(int u, Q update_query) const {
            update_query(visit[u]);
        }
        std::vector<int> inv_ids() const {
            std::vector<int> inv(n);
            for (int i = 0; i < n; ++i) inv[visit[i]] = i;
            return inv;
        }
        int get_visit_time(int u) const {
            return visit[u];
        }
        int get_leave_time(int u) const {
            return leave[u];
        }
        int get_head(int u) const {
            return head[u];
        }
        int get_kth_visited(int k) const {
            return ord[k];
        }
        int get_subtree_size(int u) const {
            return siz[u];
        }
        int get_parent(int u) const {
            return par[u];
        }
        int get_depth(int u) const {
            return dep[u];
        }
        std::vector<int> get_roots() const {
            std::vector<int> res;
            for (int i = 0; i < n; ++i) if (par[i] < 0) res.push_back(i);
            return res;
        }
    private:
        int n;
        std::vector<int> visit, leave, head, ord, siz, par, dep;
        int dfs(Graph &g, int u, int p) {
            par[u] = p;
            siz[u] = 1;
            int max_size = 0;
            for (int &v : g[u]) {
                if (v == p) continue;
                dep[v] = dep[u] + 1;
                siz[u] += dfs(g, v, u);
                if (max_size < siz[v]) {
                    max_size = siz[v];
                    std::swap(g[u].front(), v);
                }
            }
            return siz[u];
        }
        void hld(Graph &g, int u, int p, int &time) {
            visit[u] = time, ord[time] = u, ++time;
            head[u] = p >= 0 and g[p].front() == u ? head[p] : u;
            for (int v : g[u]) {
                if (v != p) hld(g, v, u, time);
            }
            leave[u] = time;
        }
};
} // namespace suisen

int main() {
    input(int, n);

    vector<vector<int>> g(n);
    rep(i, 1, n) {
        input(int, p);
        --p;
        g[p].push_back(i);
    }

    HeavyLightDecomposition hld(g);

    for (auto &l : g) {
        sort(all(l));
        // debug(l);
    }

    long long ans = 0;

    int pre = 0;
    deque<int> dq { 0 };
    while (dq.size()) {
        int p = dq.front();
        dq.pop_front();
        debug(p);
        ans += hld.dist(p, pre);
        for (int v : g[p]) {
            dq.push_back(v);
        }
        pre = p;
    }
    print(ans);

    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 20496
final_rank: 3

code_snippet: #include <bits/stdc++.h>
////#include <atcoder/all>
//using namespace atcoder;
using namespace std;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vll>;
using vvvll = vector<vvll>;
using vb = vector<bool>;
using vvb = vector<vb>;
using vvvb = vector<vvb>;
using vd = vector<double>;
using vvd = vector<vd>;
using vvvd = vector<vvd>;
#define all(A) A.begin(),A.end()
#define ALL(A) A.begin(),A.end()
#define rep(i, n) for (ll i = 0; i < (ll) (n); i++)
using pqr = priority_queue<pair<ll, ll>, vector<pair<ll, ll>>, greater<pair<ll, ll>>>;

template<class T>
bool chmax(T& p, T q) {
    if (p < q) {
        p = q;
        return 1;
    }
    else {
        return 0;
    }
}
template<class T>
bool chmin(T& p, T q) {
    if (p > q) {
        p = q;
        return 1;
    }
    else {
        return 0;
    }
}

ll gcd(ll(a), ll(b)) {
    ll c = a;
    while (a % b != 0) {
        c = a % b;
        a = b;
        b = c;
    }
    return b;
}





struct Edge {
    long long to;
};
using Graph = vector<vector<Edge>>;

/* LCA(G, root): 木 G に対する根を root として Lowest Common Ancestor を求める構造体
    query(u,v): u と v の LCA を求める。計算量 O(logn)
    前処理: O(nlogn)時間, O(nlogn)空間
*/
struct LCA {
    vector<vector<int>> parent;  // parent[k][u]:= u の 2^k 先の親
    vector<int> dist;            // root からの距離
    LCA(const Graph& G, int root = 0) { init(G, root); }

    // 初期化
    void init(const Graph& G, int root = 0) {
        int V = G.size();
        int K = 1;
        while ((1 << K) < V) K++;
        parent.assign(K, vector<int>(V, -1));
        dist.assign(V, -1);
        dfs(G, root, -1, 0);
        for (int k = 0; k + 1 < K; 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]];
                }
            }
        }
    }

    // 根からの距離と1つ先の頂点を求める
    void dfs(const Graph& G, int v, int p, int d) {
        parent[0][v] = p;
        dist[v] = d;
        for (auto e : G[v]) {
            if (e.to != p) dfs(G, e.to, v, d + 1);
        }
    }
    int dis(int u, int v) {
        int p = query(u, v);
        return -2 * dist[p] + dist[u] + dist[v];
    }
    int query(int u, int v) {
        if (dist[u] < dist[v]) swap(u, v);  // u の方が深いとする
        int K = parent.size();
        // LCA までの距離を同じにする
        for (int k = 0; k < K; k++) {
            if ((dist[u] - dist[v]) >> k & 1) {
                u = parent[k][u];
            }
        }
        // 二分探索で LCA を求める
        if (u == v) return u;
        for (int k = K - 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() {
    ll N;
    cin >> N;
    Graph G(N);
    vvll EG(N);
    
    rep(i, N - 1) {
        ll P;
        cin >> P;
        P--;
        EG[P].push_back( i + 1 );
        EG[i + 1].push_back(P );
    }
    rep(i, N)sort(all(EG[i]));
    rep(i, N)for (auto v : EG[i])G[i].push_back(Edge{ v });
    LCA L(G, 0);
    ll an = 0;
    queue<int> Q;
    Q.push(0);
    vector<bool> seen(N, false);
    vll E;
    while (!Q.empty()) {
        auto p = Q.front();
        Q.pop();
        if (seen[p])continue;
        seen[p] = 1;
        E.push_back(p);
        for (auto v : G[p]) {
            if (seen[v.to])continue;
            Q.push(v.to);
        }
    }
    rep(i, N - 1) {
        an += L.dis(E[i], E[i + 1]);
        //cout << E[i] << " " << E[i + 1] << " " << an << endl;
    }
    cout << an << endl;
}
accuracy: 1
time_ms: 30
memory_kb: 30268
final_rank: 12

code_snippet: #include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <climits>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <memory>
#include <numeric>
#include <optional>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

/* macro */

#define rep(i, a, n) for (int i = (int)(a); i < (int)(n); i++)
#define rrep(i, a, n) for (int i = ((int)(n - 1)); i >= (int)(a); i--)
#define Rep(i, a, n) for (i64 i = (i64)(a); i < (i64)(n); i++)
#define RRep(i, a, n) for (i64 i = ((i64)(n - i64(1))); i >= (i64)(a); i--)
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define Bit(n) (1LL << (n))

/* macro end */

/* template */

namespace ebi {

#ifdef LOCAL
#define debug(...)                                                      \
    std::cerr << "LINE: " << __LINE__ << "  [" << #__VA_ARGS__ << "]:", \
        debug_out(__VA_ARGS__)
#else
#define debug(...)
#endif

void debug_out() { std::cerr << std::endl; }

template <typename Head, typename... Tail>
void debug_out(Head h, Tail... t) {
    std::cerr << " " << h;
    if (sizeof...(t) > 0) std::cout << " :";
    debug_out(t...);
}

template <typename T1, typename T2>
std::ostream &operator<<(std::ostream &os, const std::pair<T1, T2> &pa) {
    return os << pa.first << " " << pa.second;
}

template <typename T1, typename T2>
std::istream &operator>>(std::istream &os, std::pair<T1, T2> &pa) {
    return os >> pa.first >> pa.second;
}

template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &vec) {
    for (std::size_t i = 0; i < vec.size(); i++)
        os << vec[i] << (i + 1 == vec.size() ? "" : " ");
    return os;
}

template <typename T>
std::istream &operator>>(std::istream &os, std::vector<T> &vec) {
    for (T &e : vec) std::cin >> e;
    return os;
}

template <typename T>
std::ostream &operator<<(std::ostream &os, const std::optional<T> &opt) {
    if (opt) {
        os << opt.value();
    } else {
        os << "invalid value";
    }
    return os;
}

using std::size_t;
using i32 = std::int32_t;
using u32 = std::uint32_t;
using i64 = std::int64_t;
using u64 = std::uint64_t;

template <class T, T init>
auto make_vector(int n) {
    return std::vector<T>(n, init);
}

template <class T, T init, typename Head, typename... Tail>
auto make_vector(Head n, Tail... ts) {
    return std::vector(n, make_vector<T, init>(ts...));
}

template <class T>
inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}

template <class T>
inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}

template <class T>
T pow(T x, i64 n) {
    T res = 1;
    while (n > 0) {
        if (n & 1) res = res * x;
        x = x * x;
        n >>= 1;
    }
    return res;
}

template <class T>
T mod_pow(T x, i64 n, i64 mod) {
    T res = 1;
    while (n > 0) {
        if (n & 1) res = (res * x) % mod;
        x = (x * x) % mod;
        n >>= 1;
    }
    return res;
}

template <class T>
T scan() {
    T val;
    std::cin >> val;
    return val;
}

template <class T>
struct Edge {
    int to;
    T cost;
    Edge(int _to, T _cost = 1) : to(_to), cost(_cost) {}
};

template <class T>
struct Graph : std::vector<std::vector<Edge<T>>> {
    using std::vector<std::vector<Edge<T>>>::vector;
    void add_edge(int u, int v, T w, bool directed = false) {
        (*this)[u].emplace_back(v, w);
        if (directed) return;
        (*this)[v].emplace_back(u, w);
    }
};

struct graph : std::vector<std::vector<int>> {
    using std::vector<std::vector<int>>::vector;
    void add_edge(int u, int v, bool directed = false) {
        (*this)[u].emplace_back(v);
        if (directed) return;
        (*this)[v].emplace_back(u);
    }
};

constexpr i64 LNF = std::numeric_limits<i64>::max() / 4;

constexpr int INF = std::numeric_limits<int>::max() / 2;

const std::vector<int> dy = {1, 0, -1, 0, 1, 1, -1, -1};
const std::vector<int> dx = {0, 1, 0, -1, 1, -1, 1, -1};

}  // namespace ebi

/*
    reference: https://scrapbox.io/data-structures/Sparse_Table
*/

namespace ebi {

template<class Band, Band (*op)(Band, Band)>
struct sparse_table {
public:
    sparse_table() = default;

    sparse_table(const std::vector<Band> &a) : n(a.size()) {
        table = std::vector(std::__lg(n) + 1, std::vector<Band>(n));
        for(int i = 0; i < n; i++) {
            table[0][i] = a[i];
        }
        for(int k = 1; (1<<k) <= n; k++) {
            for(int i = 0; i + (1<<k) <= n; i++) {
                table[k][i] = op(table[k-1][i], table[k-1][i + (1<<(k-1))]);
            }
        }
    }

    void build(const std::vector<Band> &a) {
        n = (int)a.size();
        table = std::vector(std::__lg(n) + 1, std::vector<Band>(n));
        for(int i = 0; i < n; i++) {
            table[0][i] = a[i];
        }
        for(int k = 1; (1<<k) <= n; k++) {
            for(int i = 0; i + (1<<k) <= n; i++) {
                table[k][i] = op(table[k-1][i], table[k-1][i + (1<<(k-1))]);
            }
        }
    }

    // [l, r)

    Band fold(int l, int r) {
        int k = std::__lg(r-l);
        return op(table[k][l], table[k][r-(1<<k)]);
    }
private:
    int n;
    std::vector<std::vector<Band>> table;
};

}

namespace ebi {

namespace internal_lca {
    std::pair<int,int> op(std::pair<int,int> a, std::pair<int,int> b) {
        return a.second < b.second ? a : b;
    }
}

struct lowest_common_ancestor {
public:
    lowest_common_ancestor(int _n) : n(_n), id(_n), depth(_n), g(_n) { }

    void add_edge(int u, int v) {
        g[u].emplace_back(v);
        g[v].emplace_back(u);
    }

    void build(int root = 0) {
        auto dfs = [&](auto &&self, int v, int par = -1, int d = 0) -> void {
            id[v] = int(vs.size());
            depth[v] = d;
            vs.emplace_back(v, d);
            for(const auto &nv: g[v]) if(nv != par) {
                self(self, nv, v, d+1);
                vs.emplace_back(v, d);
            }
        };
        dfs(dfs, root);
        st.build(vs);
    }

    int lca(int u, int v) {
        int l = id[u], r = id[v];
        if(r < l) std::swap(l, r);
        return st.fold(l, r+1).first;
    }

    int distance(int u, int v) {
        int w = lca(u, v);
        return depth[u] + depth[v] - 2 * depth[w];
    }

private:
    int n;
    std::vector<int> id, depth;
    std::vector<std::pair<int,int>> vs;
    graph g;
    sparse_table<std::pair<int,int>, internal_lca::op> st;
};

}

namespace ebi {

void main_() {
    int n;
    std::cin >> n;
    graph g(n);
    lowest_common_ancestor lca(n);
    rep(i,1,n) {
        int p;
        std::cin >> p;
        p--;
        g.add_edge(p, i);
        lca.add_edge(p, i);
    }
    lca.build();
    rep(i,0,n) {
        std::sort(all(g[i]));
    }
    i64 ans = 0;
    std::queue<int> que;
    int prev = -1;
    que.push(0);
    while(!que.empty()) {
        auto v = que.front();
        que.pop();
        if(prev != -1) {
            ans += lca.distance(prev, v);
        }
        for(auto nv: g[v]) if(v < nv) {
            que.push(nv);
        }
        prev = v;
    }
    std::cout << ans << '\n';
}

}  // namespace ebi

int main() {
    std::cout << std::fixed << std::setprecision(15);
    std::cin.tie(nullptr);
    std::ios::sync_with_stdio(false);
    int t = 1;
    // std::cin >> t;
    while (t--) {
        ebi::main_();
    }
    return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 52184
final_rank: 17

code_snippet: #include <stdio.h>
#include <vector>
#include <queue>
using namespace std;

int vis[204800], dist[204800], order[204800], par[24][204800];
vector<int> ed[204800];
queue<pair<int, int>> pq;

void bfs(int x) {
    int d = 0, o = 0;
    pq.push({ 0, x });
    vis[x] = 1;
    while (pq.size()) {
        x = pq.front().second;
        d = pq.front().first;
        order[o++] = x;
        pq.pop();
        for (int i : ed[x]) {
            if (!vis[i]) {
                dist[i] = d + 1;
                vis[i] = 1;
                par[0][i] = x;
                pq.push({ d + 1, i });
            }
        }
    }
}

int getdist(int x, int y) {
    int r = 0;
    for (int i = 23; i >= 0; i--) {
        if (dist[x] - dist[y] >= (1 << i)) {
            r += (1 << i);
            x = par[i][x];
        }
        else if (dist[y] - dist[x] >= (1 << i)) {
            r += (1 << i);
            y = par[i][y];
        }
    }
    for (int i = 23; i >= 0; i--) {
        if (par[i][x] != par[i][y]) {
            r += (2 << i);
            x = par[i][x];
            y = par[i][y];
        }
    }
    if (x != y) return r + 2;
    else return r;
}

int main(void) {
    int n, m, x, y;
    long long r = 0;
    scanf("%d", &n);
    for (int i = 2; i <= n; i++) {
        scanf("%d", &x);
        ed[x].push_back(i);
        ed[i].push_back(x);
    }
    bfs(1);
    par[1][0] = -1;
    x = 1;
    for (int i = 1; i < n; i++) {
        r += getdist(x, par[0][order[i]]) + 1;
        for (int j = 1; j < 24; j++) {
            if (par[j - 1][order[i]] < 0) par[j][order[i]] = -1;
            else par[j][order[i]] = par[j - 1][par[j - 1][order[i]]];
        }
        x = order[i];
    }
    printf("%lld\n", r);
    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 32320
final_rank: 14

code_snippet: #include <bits/stdc++.h>
using namespace std;

template <typename T>
struct BinaryIndexedTree {
    int N;
    vector<T>bit;
    BinaryIndexedTree(){}
    BinaryIndexedTree(int x) {
        N = x;
        bit.resize(x+1);
    }
    void add(int x,T y) {
        while(x <= N) {
            bit[x] += y;
            x += x&-x;
        }
    }
    T sum(int x) {
        T res = 0;
        while(x) {
            res += bit[x];
            x -= x&-x;
        }
        return res;
    }
    inline T sum(int l, int r) {//[l,r]
        return sum(r)-sum(l-1);
    }
    inline T operator[](int k) {
        return sum(k)-sum(k-1);
    }
};

struct HLD {
    vector<int>p,sz,in,nxt;
    BinaryIndexedTree<long long> bit;
    void dfs1(vector<vector<int>>&c,int v = 0) {
        sz[v] = 1;
        for(int &w:c[v]) {
            dfs1(c,w);
            sz[v] += sz[w];
            if(sz[w] > sz[c[v][0]]) {
                swap(w,c[v][0]);
            }
        }
    }
    void dfs2(vector<vector<int>>&c,int &t,int v = 0) {
        in[v] = t;
        t++;
        for(int w:c[v]) {
            if(w == c[v][0]) {
                nxt[w] = nxt[v];
            }
            else {
                nxt[w] = w;
            }
            dfs2(c,t,w);
        }
    }
    HLD(vector<long long>A,vector<int>p,vector<vector<int>>c):p(p) {
        int N = A.size();
        sz.resize(N,0);
        dfs1(c);
        in.resize(N,0);
        nxt.resize(N,0);
        int t = 0;
        dfs2(c,t);
        vector<long long>tmp(N);
        for(int i = 0; i < N; i++) {
            tmp[in[i]] = A[i];
        }
        BinaryIndexedTree<long long>init(tmp.size());
        for(int i = 0; i < tmp.size(); i++) {
            init.add(i+1,tmp[i]);
        }
        bit = init;
    }
    int lca(int u,int v) {
        while(true) {
            if(in[u] > in[v]) {
                swap(u,v);
            }
            if(nxt[u] == nxt[v]) {
                return u;
            }
            v = p[nxt[v]];
        }
    }
    void update(int v,long long x) {
        bit.add(in[v]+1,x);
    }
    long long query(int u,int v) {
        int w = lca(u,v);
        long long ans = 0;
        while(nxt[u] != nxt[w]) {
            ans += bit.sum(in[nxt[u]]+1,in[u]+1);
            u = p[nxt[u]];
        }
        ans += bit.sum(in[w]+1,in[u]+1);
        while(nxt[v] != nxt[w]) {
            ans += bit.sum(in[nxt[v]]+1,in[v]+1);
            v = p[nxt[v]];
        }
        ans += bit.sum(in[w]+2,in[v]+1);
        return ans;
    }
};
 
int main() {
    int n;
    cin >> n;
    vector<int>p(n,-1);
    vector<vector<int>>c(n);
    vector<long long>a(n,1);
    for(int i = 1; i < n; i++) {
        cin >> p[i];
        p[i]--;
        c[p[i]].push_back(i);
    }
    HLD hld(a,p,c);
    queue<int>que;
    vector<int>res = {0};
    que.push(0);
    while (!que.empty()) {
        int x = que.front();
        que.pop();
        for(int i = 0; i < c[x].size(); i++) {
            res.push_back(c[x][i]);
            que.push(c[x][i]);
        }
    }
    long long ans = 0;
    for(int i = 1; i < res.size(); i++) {
        ans += hld.query(res[i-1],res[i])-1;
    }
    cout << ans << endl;
}
accuracy: 1
time_ms: 30
memory_kb: 27992
final_rank: 10

code_snippet: #include <bits/stdc++.h>
using namespace std;

template <typename T>
struct BinaryIndexedTree {
    int N;
    vector<T>bit;
    BinaryIndexedTree(){}
    BinaryIndexedTree(int x) {
        N = x;
        bit.resize(x+1);
    }
    void add(int x,T y) {
        while(x <= N) {
            bit[x] += y;
            x += x&-x;
        }
    }
    T sum(int x) {
        T res = 0;
        while(x) {
            res += bit[x];
            x -= x&-x;
        }
        return res;
    }
    inline T sum(int l, int r) {//[l,r]
        return sum(r)-sum(l-1);
    }
    inline T operator[](int k) {
        return sum(k)-sum(k-1);
    }
};

struct HLD {
    vector<int>p,sz,in,nxt;
    BinaryIndexedTree<long long> bit;
    void dfs1(vector<vector<int>>&c,int v = 0) {
        sz[v] = 1;
        for(int &w:c[v]) {
            dfs1(c,w);
            sz[v] += sz[w];
            if(sz[w] > sz[c[v][0]]) {
                swap(w,c[v][0]);
            }
        }
    }
    void dfs2(vector<vector<int>>&c,int &t,int v = 0) {
        in[v] = t;
        t++;
        for(int w:c[v]) {
            if(w == c[v][0]) {
                nxt[w] = nxt[v];
            }
            else {
                nxt[w] = w;
            }
            dfs2(c,t,w);
        }
    }
    HLD(vector<long long>A,vector<int>p,vector<vector<int>>c):p(p) {
        int N = A.size();
        sz.resize(N,0);
        dfs1(c);
        in.resize(N,0);
        nxt.resize(N,0);
        int t = 0;
        dfs2(c,t);
        vector<long long>tmp(N);
        for(int i = 0; i < N; i++) {
            tmp[in[i]] = A[i];
        }
        BinaryIndexedTree<long long>init(tmp.size());
        for(int i = 0; i < tmp.size(); i++) {
            init.add(i+1,tmp[i]);
        }
        bit = init;
    }
    int lca(int u,int v) {
        while(true) {
            if(in[u] > in[v]) {
                swap(u,v);
            }
            if(nxt[u] == nxt[v]) {
                return u;
            }
            v = p[nxt[v]];
        }
    }
    void update(int v,long long x) {
        bit.add(in[v]+1,x);
    }
    long long query(int u,int v) {
        int w = lca(u,v);
        long long ans = 0;
        while(nxt[u] != nxt[w]) {
            ans += bit.sum(in[nxt[u]]+1,in[u]+1);
            u = p[nxt[u]];
        }
        ans += bit.sum(in[w]+1,in[u]+1);
        while(nxt[v] != nxt[w]) {
            ans += bit.sum(in[nxt[v]]+1,in[v]+1);
            v = p[nxt[v]];
        }
        ans += bit.sum(in[w]+2,in[v]+1);
        return ans;
    }
};
 
int main() {
    int n;
    cin >> n;
    vector<int>p(n,-1);
    vector<vector<int>>c(n);
    vector<long long>a(n,1);
    for(int i = 1; i < n; i++) {
        cin >> p[i];
        p[i]--;
        c[p[i]].push_back(i);
    }
    HLD hld(a,p,c);
    queue<int>que;
    vector<int>res = {0};
    que.push(0);
    while (!que.empty()) {
        int x = que.front();
        que.pop();
        for(int i = 0; i < c[x].size(); i++) {
            res.push_back(c[x][i]);
            que.push(c[x][i]);
        }
    }
    int ans = 0;
    for(int i = 1; i < res.size(); i++) {
        ans += hld.query(res[i-1],res[i])-1;
    }
    cout << ans << endl;
}
accuracy: 0.5901639344262295
time_ms: 30
memory_kb: 26880
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (int i = 0; i < (n); i++)
#define ALL(x) x.begin(), x.end()
// clang-format off
template <class T> using V = vector<T>;
template <class T, class U> ostream &operator<<(ostream &os, const pair<T, U> &p) { return os << "(" << p.first << ", " << p.second << ")"; }
template <class T> ostream &operator<<(ostream &os, const vector<T> &v) { os << "[ "; for (auto &z : v) os << z << " "; os << "]"; return os; }
#ifdef _RUTHEN
#define show(x) cerr << __LINE__ << " : " << #x << " = " << x << endl;
#else
#define show(x)
#endif
// clang-format on

struct lowest_common_ancestor {
    vector<vector<int>> G;
    vector<int> depth;
    vector<vector<int>> parent;
    int n, LOG;  // n = 頂点数, root = 根とする頂点番号, LOG = ダブリングする深さ
    lowest_common_ancestor(int n) : n(n), LOG(32 - __builtin_clz(n)), G(n) {}
    void add_edge(int u, int v) {
        // 無向辺{u, v}を加える
        G[u].push_back(v);
        G[v].push_back(u);
    }
    void build(int root = 0) {
        depth.assign(n, 0);
        parent.assign(LOG, vector<int>(n, 0));
        dfs(root, -1, 0);
        for (int k = 0; k + 1 < LOG; k++) {
            for (int v = 0; v < n; v++) {
                if (parent[k][v] < 0)
                    parent[k + 1][v] = -1;
                else
                    parent[k + 1][v] = parent[k][parent[k][v]];
            }
        }
    }
    void dfs(int cur, int par, int d) {
        parent[0][cur] = par;
        depth[cur] = d;
        for (auto &nx : G[cur]) {
            if (nx != par) dfs(nx, cur, d + 1);
        }
    }
    int lca(int u, int v) {
        assert((int)depth.size() == n);
        if (depth[u] > depth[v]) swap(u, v);
        // depth[u] <= depth[v](vの方が深い)
        // 同じ深さまでvが登る
        for (int k = 0; k < LOG; k++) {
            if ((depth[v] - depth[u]) >> k & 1) {
                v = parent[k][v];
            }
        }
        if (u == v) return u;
        for (int k = LOG - 1; k >= 0; k--) {
            if (parent[k][u] != parent[k][v]) {
                u = parent[k][u];
                v = parent[k][v];
            }
        }
        return parent[0][u];
    }
};

const int INF = 1 << 30;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;
    cin >> n;
    V<V<int>> G(n);
    lowest_common_ancestor lca(n);
    for (int i = 1; i < n; i++) {
        int p;
        cin >> p;
        p--;
        G[i].push_back(p);
        G[p].push_back(i);
        lca.add_edge(i, p);
    }
    lca.build();
    rep(i, n) sort(ALL(G[i]));
    queue<int> que;
    V<int> d(n, INF);
    d[0] = 0;
    ll ans = 0;
    que.push(0);
    int las = 0;
    while (!que.empty()) {
        int v = que.front();
        que.pop();
        int lcav = lca.lca(las, v);
        show(v) show(las) show(lcav);
        ans += d[las] - d[lcav];
        ans += d[v] - d[lcav];
        for (auto &nx : G[v]) {
            if (d[nx] == INF) {
                d[nx] = d[v] + 1;
                que.push(nx);
            }
        }
        las = v;
    }
    cout << ans << '\n';
    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 27668
final_rank: 9

code_snippet: #include <bits/stdc++.h>
using namespace std;

struct LCA {
  int n, root, h;
  vector<vector<int>> g, par;
  vector<int> dep;
  LCA(int _n = 1, int r = 0) : n(_n), root(r), g(_n), dep(_n) {
    h = 1;
    while ((1 << h) <= n) ++h;
    par.assign(h, vector<int>(n, -1));
  }
  LCA(const vector<vector<int>> &_g, const int r = 0)
      : n(_g.size()), root(r), g(_g), dep(_g.size()) {
    h = 1;
    while ((1 << h) <= n) ++h;
    par.assign(h, vector<int>(n, -1));
    build();
  }
  void add(int a, int b) {
    g[a].push_back(b);
    g[b].push_back(a);
  }
  void dfs(int now, int bf, int d) {
    par[0][now] = bf;
    dep[now] = d;
    for (int &to : g[now])
      if (to != bf) dfs(to, now, d + 1);
  }
  void build() {
    dfs(root, -1, 0);
    for (int i = 0; i + 1 < h; ++i)
      for (int j = 0; j < n; ++j) {
        if (par[i][j] < 0)
          par[i + 1][j] = -1;
        else
          par[i + 1][j] = par[i][par[i][j]];
      }
  }
  int calc(int x, int y) {
    if (dep[x] > dep[y]) swap(x, y);
    for (int i = 0; i < h; ++i)
      if ((dep[y] - dep[x]) >> i & 1) y = par[i][y];
    if (x == y) return x;
    for (int i = h - 1; i >= 0; --i)
      if (par[i][x] != par[i][y]) {
        x = par[i][x];
        y = par[i][y];
      }
    return par[0][y];
  }
  inline int dist(int x, int y) {
    return dep[x] + dep[y] - 2 * dep[calc(x, y)];
  }

  inline int operator[](const int &k) { return (dep.at(k)); }
};

int n;
vector<int> par;
LCA lca;

long long solve();

int main() {
  cin >> n;
  lca = LCA(n);
  par.assign(n, -1);
  for (int i = 1; i < n; ++i) {
    cin >> par[i];
    lca.add(i, --par[i]);
  }
  cout << solve() << endl;
  return 0;
}

long long solve() {
  long long res = 0;
  lca.build();
  vector<int> id(n, 0);
  vector<vector<int>> memo(n);
  for (int i = 0; i < n; ++i) memo[lca[i]].push_back(i);
  for (int i = 0, cnt = 0, bf = -1; i < n; ++i) {
    sort(memo[i].begin(), memo[i].end(), [&](int l, int r) {
      if (id[par[l]] != id[par[r]]) return id[par[l]] < id[par[r]];
      return l < r;
    });
    for (auto p : memo[i]) {
      id[p] = cnt++;
      if (bf >= 0) res += lca.dist(bf, p);
      bf = p;
    }
  }
  return res;
}
accuracy: 1
time_ms: 30
memory_kb: 28020
final_rank: 11

code_snippet: // #include "atcoder/all"
#include <iostream> // cout, endl, cin
#include <string> // string, to_string, stoi
#include <vector> // vector
#include <algorithm> // min, max, swap, sort, reverse, lower_bound, upper_bound
#include <utility> // pair, make_pair
#include <tuple> // tuple, make_tuple
#include <cstdint> // int64_t, int*_t
#include <cstdio> // printf
#include <map> // map
#include <queue> // queue, priority_queue
#include <set> // set
#include <stack> // stack
#include <deque> // deque
#include <unordered_map> // unordered_map
#include <unordered_set> // unordered_set
#include <bitset> // bitset
#include <cctype> // isupper, islower, isdigit, toupper, tolower
#include <iomanip> // setprecision
#include <complex> // complex
#include <math.h>
#include <functional>
#include <cassert>
using namespace std;
// using namespace atcoder;
using ll = long long;
using P = pair<ll,ll>;
constexpr ll INF = 1e15;
constexpr ll LLMAX = 9223372036854775807;
constexpr int inf = 1e9;
// constexpr ll mod = 1000000007;
constexpr ll mod = 998244353;
// 右下左上
const int dx[8] = {1, 0, -1, 0,1,1,-1,-1};
const int dy[8] = {0, 1, 0, -1,1,-1,1,-1};
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
#define eol "\n"
// ---------------------------------------------------------------------------

struct LCA {
    vector<vector<int>> parent; // parent[k][u] := u の 2^k 先の親
    vector<int> dist; // root からの距離
    LCA(const vector<vector<int>> &G,int root = 0){ init(G,root); }

    // 初期化
    void init(const vector<vector<int>> &G,int root = 0){
        int V = G.size();
        int K = 1;
        while((1 << K) < V) K++;
        parent.assign(K, vector<int>(V, -1));
        dist.assign(V,-1);
        dfs(G,root,-1,0);
        for(int k=0; k<K-1; 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]];
                }
            }
        }
    }

    // 根からの距離と一つ先の頂点を求める
    void dfs(const vector<vector<int>> &G, int v, int p,int d){
        // 一つ先の頂点
        parent[0][v] = p;
        dist[v] = d;
        for(auto nv: G[v]){
            if(nv != p) dfs(G,nv,v,d+1);
        }
    }

    int query(int u,int v){
        if(dist[u] < dist[v]) swap(u,v);
        int K = parent.size();
        // LCAまでの距離を同じにする
        for(int k=0; k<K; k++){
            if((dist[u]-dist[v]) >> k & 1){
                u = parent[k][u];
            }
        }
        // 二分探索で LCA を求める
        if(u == v) return u;
        for(int k=K-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(){
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int N;
  cin >> N;
  vector<vector<int>> G(N);
  for(int i=0; i<N-1; i++){
    int p;
    cin >> p;
    p--;
    G[p].emplace_back(i+1);
    G[i+1].emplace_back(p);
  }
  LCA lca(G);
  for(int i=0; i<N; i++) sort(G[i].begin(),G[i].end());
  int pos = 0;
  queue<int> que;
  vector<int> dist(N,inf);
  dist[0] = 0;
  que.emplace(0);
  ll ans = 0;
  while(que.size()){
    int v = que.front();
    que.pop();
    ans += dist[v] + dist[pos] - 2*dist[lca.query(v,pos)];
    for(int nv : G[v]){
      if(chmin(dist[nv],dist[v]+1)){
        que.emplace(nv);
      }
    }
    pos = v;
  }
  cout << ans << endl;
  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 23536
final_rank: 6

code_snippet: #include<bits/stdc++.h>
using namespace std;

using ll = long long;
const int INF = 1e9;
const ll inf = 1LL<<55;
struct Edge {
  long long to;
};
using Graph = vector<vector<Edge>>;

/*
  LCA(G, root) : calculate Lowerst common ancestor with tree G, root
  query(u, v) : calculate LCA of u and v by O(logn)
*/
struct LCA {
  vector<vector<int>> parent; // parent[k][u] := 2^k parent of u
  vector<int> dist; // dist[i] := distance of i from root
  LCA(const Graph &G, int root = 0) {
    init(G, root);
  }

  void init(const Graph &G, int root = 0) {
    int V = (int)G.size();
    int K = 1;
    while ((1<<K) < V) {
      K++;
    }
    parent.assign(K, vector<int>(V, -1));
    dist.assign(V, -1);
    dfs(G, root, -1, 0);
    for (int k=0; k+1<K; k++) {
      for (int v=0; v<V; v++) {
        if (parent.at(k).at(v) < 0) {
          parent.at(k+1).at(v) = -1;
        } else {
          parent.at(k+1).at(v) = parent.at(k).at(parent.at(k).at(v));
        }
      }
    }
  }

  void dfs(const Graph &G, int v, int p, int d) {
    parent.at(0).at(v) = p;
    dist.at(v) = d;
    for (auto e : G.at(v)) {
      if (e.to != p) dfs(G, e.to, v, d+1);
    }
  }

  int query(int u, int v) {
    if (dist.at(u) < dist.at(v)) swap(u, v);
    int K = parent.size();
    for (int k=0; k<K; k++) {
      if ((dist.at(u) - dist.at(v)) >> k & 1) {
        u = parent.at(k).at(u);
      }
    }
    if (u == v) return u;
    for (int k=K-1; k >= 0; k--) {
      if (parent.at(k).at(u) != parent.at(k).at(v)) {
        u = parent.at(k).at(u);
        v = parent.at(k).at(v);
      }
    }
    return parent.at(0).at(u);
  }

  int get_dist(int u, int v) {
    return dist.at(u) + dist.at(v) - 2*dist.at(query(u, v));
  }

  bool in_on_path(int u, int v, int a) {
    return get_dist(u, a) + get_dist(a, v) == get_dist(u, v);
  }
};


int main() {
  int n; cin >> n;
  Graph g(n);
  vector<vector<int>> G(n);
  for (int i=1; i<n; i++) {
    int p; cin >> p; p--;
    G[i].push_back(p);
    G[p].push_back(i);
    g[i].push_back({p});
    g[p].push_back({i});
  }
  LCA lca(g);
  for (int i=0; i<n; i++) sort(G[i].begin(), G[i].end());
  vector<int> d(n);
  vector<vector<int>> ord(n);
  auto dfs = [&](auto&&dfs, int v, int p) -> void {
    if (p == -1) d[v] = 0;
    else d[v] = d[p] + 1;
    ord[d[v]].push_back(v);
    for (auto e : G[v]) if (e != p) {
      dfs(dfs, e, v);
    }
  };
  dfs(dfs, 0, -1);
  vector<int> c;
  for (auto a : ord) for (auto b : a) c.push_back(b);
  ll ans = 0;
  for (int i=1; i<c.size(); i++) ans += lca.get_dist(c[i-1], c[i]);
  cout << ans << endl;
}
accuracy: 1
time_ms: 50
memory_kb: 35624
final_rank: 15