MOD = 10**9 + 7 def main(): import sys input = sys.stdin.read().split() idx = 0 N = int(input[idx]) idx += 1 p = list(map(int, input[idx:idx+N])) # Precompute factorials modulo MOD up to N fact = [1] * (N + 1) for i in range(1, N + 1): fact[i] = fact[i - 1] * i % MOD # Fenwick Tree implementation class FenwickTree: def __init__(self, size): self.size = size self.tree = [0] * (size + 1) def update(self, index, delta=1): 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 ft = FenwickTree(N) for num in p: ft.update(num) rank = 0 for i in range(N): current = p[i] # Query the number of elements less than current c = ft.query(current - 1) remaining = N - i - 1 if remaining >= 0: fact_val = fact[remaining] if remaining < N else 0 term = c * fact_val % MOD rank = (rank + term) % MOD # Remove current from the Fenwick Tree ft.update(current, -1) print((rank + 1) % MOD) if __name__ == '__main__': main()