class FenwickTree: def __init__(self, size): self.size = size self.tree = [0] * (size + 1) # 1-based indexing def update(self, index, delta): while index <= self.size: self.tree[index] += delta index += index & -index def query(self, index): res = 0 while index > 0: res += self.tree[index] index -= index & -index return res def main(): import sys input = sys.stdin.read data = input().split() n = int(data[0]) p = list(map(int, data[1:1+n])) # Precompute factorials max_n = n fact = [1] * (max_n + 1) for i in range(1, max_n + 1): fact[i] = fact[i-1] * i ft = FenwickTree(n) result = 0 for i in range(n): current = p[i] # Compute the number of elements less than current that are still available k = ft.query(current - 1) remaining = current - 1 - k rem = n - i - 1 if rem >= 0: result += remaining * fact[rem] ft.update(current, 1) print(result + 1) if __name__ == "__main__": main()