## https://yukicoder.me/problems/no/1300 MOD = 998244353 class SegmentTree: """ 非再帰版セグメント木。 更新は「加法」、取得は「最大値」のもの限定。 """ def __init__(self, init_array): n = 1 while n < len(init_array): n *= 2 self.size = n self.array = [0] * (2 * self.size) for i, a in enumerate(init_array): self.array[self.size + i] = a end_index = self.size start_index = end_index // 2 while start_index >= 1: for i in range(start_index, end_index): self.array[i] = (self.array[2 * i] + self.array[2 * i + 1]) % MOD end_index = start_index start_index = end_index // 2 def add(self, x, a): index = self.size + x self.array[index] += a while index > 1: index //= 2 self.array[index] = (self.array[2 * index] + self.array[2 * index + 1]) % MOD def get_sum(self, l, r): L = self.size + l; R = self.size + r # 2. 区間[l, r)の最大値を求める s = 0 while L < R: if R & 1: R -= 1 s += self.array[R] s %= MOD if L & 1: s += self.array[L] s %= MOD L += 1 L >>= 1; R >>= 1 return s def main(): N = int(input()) A = list(map(int, input().split())) # 座標圧縮 a_set = set(A) a_set.add(max(A) + 1) a_set.add(max(A) + 2) a_list = list(a_set) a_list.sort() a_map = {} for i, a in enumerate(a_list): a_map[a] = i a_max = len(a_list) # forward方向 forward_nums = [0] * N forward_values = [0] * N num_seg_tree = SegmentTree([0] * a_max) value_seg_tree = SegmentTree([0] * a_max) for i in range(N): a = A[i] a_ = a_map[a] s = num_seg_tree.get_sum(a_ + 1, a_max) v = value_seg_tree.get_sum(a_ + 1, a_max) forward_nums[i] = s forward_values[i] = v num_seg_tree.add(a_, 1) value_seg_tree.add(a_, a) # backward方向 backward_nums = [0] * N backward_values = [0] * N num_seg_tree = SegmentTree([0] * a_max) value_seg_tree = SegmentTree([0] * a_max) for i in reversed(range(N)): a = A[i] a_ = a_map[a] if a_ > 0: s = num_seg_tree.get_sum(0, a_) v = value_seg_tree.get_sum(0, a_) else: s = 0 v = 0 backward_nums[i] = s backward_values[i] = v num_seg_tree.add(a_, 1) value_seg_tree.add(a_, a) answer = 0 for i in range(N): a = A[i] f_n = forward_nums[i] f_v = forward_values[i] b_n = backward_nums[i] b_v = backward_values[i] ans1 = (a * f_n) % MOD ans1 *= b_n ans1 %= MOD ans2 = (f_v * b_n) % MOD ans3 = (b_v * f_n) % MOD answer += (ans1 + ans2) % MOD answer %= MOD answer += ans3 answer %= MOD print(answer) if __name__ == "__main__": main()