U648803 不下降子序列数量 题解

· · 题解

#include <bits/stdc++.h>
using namespace std;
#define MOD 998244353
int main() {
    int n;
    cin >> n;
    vector<int> a(n + 1, 0);
    for (int i = 1; i <= n; ++i) cin >> a[i];
    vector<int> b = a;
    sort(b.begin() + 1, b.end());
    map<int, int> mp;
    for (int i = 1, j = 1; i <= n; ++i)
        if (b[i] != b[i-1])
            mp[b[i]] = j++;
    for (int i = 1; i <= n; ++i) a[i] = mp[a[i]];
//  for (int i = 1; i <= n; ++i) cout << a[i] << " ";
//  puts("");
    vector<int> f(n + 1, 0);
    auto update = [&](int i, int x) {
        for (; i <= n; i += i&-i) (f[i] += x) %= MOD;
    };
    auto query = [&](int i) {
        int ret = 0;
        for (; i; i -= i&-i) (ret += f[i]) %= MOD;
        return ret;
    };
    int ans = 1;
    update(a[1], 1);
    for (int i = 2; i <= n; ++i) {
        int q = query(a[i]) + 1;
        update(a[i], q);
        (ans += q) %= MOD;
    }
    cout << ans << endl;
    return 0;
}