Official

A - LR Constraints Editorial by evima


It is important to note that for \(i\) and \(j\) such that \(i \neq j\), the integer written on the \(i\)-th card from the left does not affect the integer written on the \(j\)-th card. Let us find the number of different integers that we can write on each card.

We can write an integer \(x\) on the \(i\)-th card from the left if and only if the condition 1 below and one of the conditions 2 and 3 are satisfied.

  1. There is no integer \(y\) such that \(x \neq y\) and \(k_y = i\).
  2. \(c_x\) is L and \(k_x \leq i\).
  3. \(c_x\) is R and \(i \leq k_x\).

This approach works in \(O(NK)\) time, which is fast enough.

Sample Implementation (C++)

#include <iostream>
#include <vector>
using ll = long long;
using namespace std;

int main()
{
    int N, K;
    cin >> N >> K;
    vector<int> a(N, 0);
    vector<int> b(N, 0);
    for (int i = 0; i < K; i++)
    {
        char c;
        int k;
        cin >> c >> k;
        k--;
        b[k] = 1;
        for (int j = 0; j < N; j++)
        {
            if (c == 'L' && k <= j)
                a[j]++;
            if (c == 'R' && j <= k)
                a[j]++;
        }
    }
    const ll MOD = 998244353;
    ll ans = 1;
    for (int i = 0; i < N; i++)
        if (!b[i])
            ans = ans * a[i] % MOD;

    cout << ans << endl;
    return 0;
}

posted:
last update: