import bisect from collections import defaultdict def main(): import sys input = sys.stdin.read().split() n = int(input[0]) a = list(map(int, input[1:n+1])) counter = defaultdict(int) for num in a: counter[num] += 1 threshold = 200 total = 0 for num in counter: m = counter[num] s = [1 if x == num else -1 for x in a] prefix = [0] for x in s: prefix.append(prefix[-1] + x) sorted_unique_prefix = sorted(set(prefix)) mapping = {v: i + 1 for i, v in enumerate(sorted_unique_prefix)} max_rank = len(sorted_unique_prefix) + 2 fenwick = [0] * (max_rank + 1) def update(idx, val=1): while idx <= max_rank: fenwick[idx] += val idx += idx & -idx def query(idx): res = 0 while idx > 0: res += fenwick[idx] idx -= idx & -idx return res total_current = 0 current_sum = 0 update(mapping[0]) for i in range(len(s)): current_sum += s[i] p = current_sum if p not in mapping: rank = bisect.bisect_left(sorted_unique_prefix, p) + 1 else: rank = mapping[p] count = query(rank - 1) total_current += count update(rank) total += total_current print(total) if __name__ == '__main__': main()