class Range def upper_bound ac, wa = self.begin, self.end wa += 1 unless self.exclude_end? while ac + 1 < wa wj = (ac + wa) / 2 if yield(wj) ac = wj else wa = wj end end ac end end N = gets.to_i A = gets.split.map(&:to_i) counts = [[0, 0]] A.each do |x| a, b = counts[-1] case x when 1 counts << [a + 1, b] when 2 counts << [a, b + 1] else counts << [a, b] end end ans = 0 (0 .. N - 2).each do |l| a, b = counts[l] r1 = (l + 1 .. N).upper_bound { |i| a == counts[i][0] } r2 = (r1 .. N).upper_bound { |i| b == counts[i][1] } ans += 1 * (r1 - l - 1) + 2 * (r2 - r1) + 3 * (N - r2) end puts ans