import bisect def main(): import sys input = sys.stdin.read().split() n = int(input[0]) A = list(map(int, input[1:n+1])) from collections import defaultdict pos_dict = defaultdict(list) for idx, num in enumerate(A): pos_dict[num].append(idx) total = 0 for x in pos_dict: transformed = [] for num in A: if num == x: transformed.append(1) else: transformed.append(-1) prefix_sums = [0] for t in transformed: prefix_sums.append(prefix_sums[-1] + t) sorted_ps = sorted(set(prefix_sums)) rank = {v: i+1 for i, v in enumerate(sorted_ps)} max_rank = len(sorted_ps) + 2 class BIT: def __init__(self, size): self.size = size self.tree = [0]*(size+1) def update(self, idx, delta=1): while idx <= self.size: self.tree[idx] += delta idx += idx & -idx def query(self, idx): res = 0 while idx > 0: res += self.tree[idx] idx -= idx & -idx return res bit = BIT(max_rank) current_sum = 0 bit.update(rank[0]) cnt = 0 for i in range(1, len(prefix_sums)): s = prefix_sums[i] target_rank = bisect.bisect_left(sorted_ps, s) cnt += bit.query(target_rank) r = rank[s] bit.update(r) total += cnt print(total) if __name__ == "__main__": main()