Official

C - Not All Editorial by en_translator


It is sufficient to remove the last element of \(A\) until there exists an integer between \(1\) and \(M\) that is not contained in \(A\). Specifically, this can be described as the following algorithm:

  1. Receive integers \(N\) and \(M\) and an array \(A\) as an input.
  2. Prepare a variable \(\texttt{ans}\) initialized with \(0\).
  3. Prepare an array \(\texttt{exist}\) of \(M\) boolean values, every element initialized with \(\texttt{false}\).
  4. For \(i=1,2,\dots,|A|\) (where \(|A|\) denotes the current length of \(|A|\)), set \(\texttt{exist}[A[i]]\) to \(\texttt{true}\).
  5. If the array \(\texttt{exist}\) contains an element \(\texttt{false}\), print the value \(\texttt{ans}\) and terminate the program. Otherwise, remove the last element of \(A\), add \(1\) to \(\texttt{ans}\), and proceed to step 3.

For more details on implementation, please refer to the sample code in C++ and Python. If your language adopts \(0\)-based indexing (the index of an array starts with \(0\)), it is effective to subtract \(1\) from every element once you receive \(A\) as input, in order to avoid implementation mistakes regarding indices.

Sample code (C++):

#include <bits/stdc++.h>

using namespace std;

int main() {
    int n, m;
    cin >> n >> m;
    vector<int> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        --a[i];
    }

    int ans = 0;
    while (true) {
        vector<bool> exist(m);
        for (int i: a) exist[i] = true;
        bool ok = false;
        for (bool b: exist) {
            if (!b) ok = true;
        }
        if (ok) break;
        ++ans;
        a.pop_back();
    }

    cout << ans << endl;
}

Sample code (Python) :

n, m = map(int, input().split())
a = list(map(int, input().split()))
for i in range(n):
  a[i] -= 1

ans = 0
while True:
    exist = [False] * m
    for i in a:
        exist[i] = True
    ok = False
    for b in exist:
      if not b:
        ok = True
    if ok:
        break
    ans += 1
    a.pop()

print(ans)

posted:
last update: