## https://yukicoder.me/problems/no/778 import sys sys.setrecursionlimit(201000) class BinaryIndexTree: """ フェニック木(BinaryIndexTree)の基本的な機能を実装したクラス """ def __init__(self, size): self.size = size self.array = [0] * (size + 1) def add(self, x, a): index = x while index <= self.size: self.array[index] += a index += index & (-index) def sum(self, x): index = x ans = 0 while index > 0: ans += self.array[index] index -= index & (-index) return ans def least_upper_bound(self, value): if self.sum(self.size) < value: return -1 elif value <= 0: return 0 m = 1 while m < self.size: m *= 2 k = 0 k_sum = 0 while m > 0: k0 = k + m if k0 < self.size: if k_sum + self.array[k0] < value: k_sum += self.array[k0] k += m m //= 2 if k < self.size: return k + 1 else: return -1 def main(): N = int(input()) A = list(map(int, input().split())) euler_tour = [[-1, -1] for _ in range(N)] next_nodes = [[] for _ in range(N)] for i, a in enumerate(A): next_nodes[a].append(i + 1) def dfs(next_nodes, v, euler_index, euler_tour): euler_tour[v][0] = euler_index euler_index += 1 for n in next_nodes[v]: euler_index = dfs(next_nodes, n, euler_index, euler_tour) euler_tour[v][1] = euler_index euler_index += 1 return euler_index euler_index = dfs(next_nodes, 0, 0, euler_tour) bit = BinaryIndexTree(euler_index) # 番号の大きい順かあ処理 answer = 0 for i in reversed(range(N)): in_, out_ = euler_tour[i] start = bit.sum(in_) end = bit.sum(out_) child_num = end - start answer += child_num bit.add(in_ + 1, 1) print(answer) if __name__ == '__main__': main()