class Fenwick_Tree: def __init__(self, n): self._n = n self.data = [0] * n def add(self, p, x): assert 0 <= p < self._n p += 1 while p <= self._n: self.data[p - 1] += x p += p & -p def sum(self, l, r): assert 0 <= l <= r <= self._n return self._sum(r) - self._sum(l) def _sum(self, r): s = 0 while r > 0: s += self.data[r - 1] r -= r & -r return s def get_size(self, x): x = self.find(x) while r > 0: s += self.data[r - 1] r -= r & -r return s def get(self, k): k += 1 x, r = 0, 1 while r < self._n: r <<= 1 len = r while len: if x + len - 1 < self._n: if self.data[x + len - 1] < k: k -= self.data[x + len - 1] x += len len >>= 1 return x from bisect import * from copy import deepcopy def compress(lst): """ B: lstを座圧したリスト D: indexから元の値を取得する辞書 """ B = [] D = dict() vals = deepcopy(lst) vals = list(set(vals)) vals.sort() for i in range(len(lst)): ind = bisect_left(vals, lst[i]) B.append(ind) for i in range(len(B)): D[lst[i]] = B[i] return B, D, vals N = int(input()) A = list(map(int, input().split())) D, _, _ = compress(A) TLn, TRn = Fenwick_Tree(N), Fenwick_Tree(N) TLs, TRs = Fenwick_Tree(N), Fenwick_Tree(N) for d, a in zip(D, A): TRs.add(d, a) TRn.add(d, 1) ans = 0 mod = 998244353 for d, a in zip(D, A): L = TLn.sum(d + 1, N) R = TRn.sum(0, d) vL = TLs.sum(d + 1, N) vR = TRs.sum(0, d) ans += a * L * R + L * vR + R * vL ans %= mod TLn.add(d, 1) TLs.add(d, a) TRn.add(d, -1) TRs.add(d, -a) print(ans)