import std.stdio, std.string, std.conv; import std.range, std.algorithm, std.array, std.typecons, std.container; import std.math, std.numeric, core.bitop; void main() { int n; scan(n); auto a = readln.split.to!(int[]); long ans = solve(n, a); ans.writeln; } long solve(int n, int[] a) { auto ch = new int[][](n, 0); foreach (i, ai; a) { ch[ai] ~= i.to!int + 1; } int[] et; auto begin = new int[](n); auto end = new int[](n); void dfs(int v) { begin[v] = et.length.to!int; et ~= v; foreach (u ; ch[v]) { dfs(u); et ~= v; } end[v] = et.length.to!int; } dfs(0); debug { stderr.writeln(et); stderr.writeln(begin); stderr.writeln(end); } auto bit = FenwickTree!(int)(2*n); long ans; foreach_reverse (i ; 0 .. n) { int cnt = bit.sum(end[i]) - bit.sum(begin[i]); ans += cnt; bit.add(begin[i], 1); } return ans; } struct FenwickTree(T) { private { int _size; T[] _data; } this(int N) { _size = N; _data = new T[](_size + 1); } void add(int i, T x) { i++; while (i <= _size) { _data[i] += x; i += i & (-i); } } T sum(int r) { T res = 0; while (r > 0) { res += _data[r]; r -= r & (-r); } return res; } } void scan(T...)(ref T args) { import std.stdio : readln; import std.algorithm : splitter; import std.conv : to; import std.range.primitives; auto line = readln().splitter(); foreach (ref arg; args) { arg = line.front.to!(typeof(arg)); line.popFront(); } assert(line.empty); } void fillAll(R, T)(ref R arr, T value) { static if (is(typeof(arr[] = value))) { arr[] = value; } else { foreach (ref e; arr) { fillAll(e, value); } } }