class FenwickTree: def __init__(self, size): self.n = size self.tree = [0] * (self.n + 2) # 1-based indexing, handle up to size+1 def add(self, idx, delta): idx += 1 # Convert to 1-based while idx <= self.n + 1: self.tree[idx] += delta idx += idx & -idx def sum_query(self, idx): res = 0 idx += 1 # Convert to 1-based if idx < 1: return 0 while idx > 0: res += self.tree[idx] idx -= idx & -idx return res def main(): import sys input = sys.stdin.read().split() ptr = 0 N = int(input[ptr]) ptr += 1 A = list(map(int, input[ptr:ptr + N-1])) ptr += N-1 children = [[] for _ in range(N)] for i in range(N-1): parent = A[i] child = i + 1 children[parent].append(child) fenwick = FenwickTree(N) ans = 0 stack = [(0, False)] while stack: node, visited = stack.pop() if not visited: current_sum = fenwick.sum_query(node - 1) ans += current_sum fenwick.add(node, 1) stack.append((node, True)) for child in reversed(children[node]): stack.append((child, False)) else: fenwick.add(node, -1) print(ans) if __name__ == '__main__': main()