class BinaryIndexedTree: """一点加算、区間総和クエリをそれぞれO(logN)で答えるデータ構造。""" def __init__(self, n): self.size = n self.bit = [0] * (n + 1) def build(self, array): """arrayを初期値とするBinaryIndexedTreeを構築する。O(N)""" for i, val in enumerate(array): self.bit[i + 1] = val for i in range(1, self.size): if i + (i & -i) > self.size: continue self.bit[i + (i & -i)] += self.bit[i] def _sum(self, i): s = 0 while i > 0: s += self.bit[i] i -= i & -i return s def add(self, i, val): """i番目の要素にvalを加算する。O(logN)""" i += 1 while i <= self.size: self.bit[i] += val i += i & -i def sum(self, l, r): """区間[l, r)の和を求める。O(logN)""" return self._sum(r) - self._sum(l) n = int(input()) a = list(map(int, input().split())) MOD = 998244353 sorted_a = sorted([(a[i], i) for i in range(n)]) + [(-1, -1)] bitl_cnt = BinaryIndexedTree(n) bitl_val = BinaryIndexedTree(n) bitl_cnt.build([1] * n) bitl_val.build([val for val in a]) bits_cnt = BinaryIndexedTree(n) bits_val = BinaryIndexedTree(n) ans = 0 i = 0 while i < n: val, idx = sorted_a[i] idxs = [idx] while sorted_a[i][0] == sorted_a[i + 1][0]: i += 1 idxs.append(sorted_a[i][1]) for idx in idxs: bitl_cnt.add(idx, -1) bitl_val.add(idx, -val) for idx in idxs: cnt_large = bitl_cnt.sum(0, idx) sum_large = bitl_val.sum(0, idx) cnt_small = bits_cnt.sum(idx + 1, n) sum_small = bits_val.sum(idx + 1, n) ans += val * (cnt_large) * (cnt_small) ans += cnt_large * sum_small + cnt_small * sum_large ans %= MOD for idx in idxs: bits_cnt.add(idx, 1) bits_val.add(idx, val) i += 1 print(ans)