#include #include #include using namespace std; using ll = long long; constexpr ll MOD = 998244353; template struct FenwickTree{ const int n; vector arr; FenwickTree() = default; FenwickTree(int n): n(n), arr(vector(n+1, 0)){} void add(int ind, T x){ for(int i = ind+1; i <= n; i += i & (-i)){ arr[i] += x; } } T sum_sub(int end){ T res = 0; for(int i = end; i > 0; i -= i & (-i)){ res += arr[i]; } return res; } T sum(int start, int end){ return sum_sub(end) - sum_sub(start); } int lower_bound(T w){ if(w <= 0) return 0; int x = 0; int k = 1 << 30; while(k > n) k /= 2; for(; k > 0; k /= 2){ if(x+k <= n && arr[x+k] < w){ w -= arr[x+k]; x += k; } } return x; } }; template vector compress(vector &x){ vector vals = x; sort(vals.begin(), vals.end()); vals.erase(unique(vals.begin(), vals.end()), vals.end()); for(auto &p: x){ p = lower_bound(vals.begin(), vals.end(), p) - vals.begin(); } return vals; } int main(){ int n; cin >> n; vector a(n); for(auto &it: a) cin >> it; auto val = compress(a); ll ans = 0; FenwickTree cntl(n+1), cntr(n+1); FenwickTree totl(n+1), totr(n+1); for(int i = 0; i < n; i++){ cntr.add(a[i], 1); totr.add(a[i], val[a[i]]); } for(int i = 0; i < n; i++){ cntr.add(a[i], -1); totr.add(a[i], -val[a[i]]); ans += (cntl.sum(a[i]+1, n+1)*cntr.sum(0, a[i]))%MOD*val[a[i]]; ans %= MOD; // cout << ans << " " << val[a[i]] << " "; if(cntl.sum(a[i]+1, n+1)*cntr.sum(0, a[i]) > 0){ ans += totr.sum(0, a[i])%MOD*cntl.sum(a[i]+1, n+1); ans %= MOD; ans += totl.sum(a[i]+1, n+1)%MOD*cntr.sum(0, a[i]); ans %= MOD; } // cout << cntl.sum(a[i]+1, n+1) << " " << cntr.sum(0, a[i]) << " " << ans << endl; cntl.add(a[i], 1); totl.add(a[i], val[a[i]]); } cout << ans << endl; return 0; }