Official

C - Except and Min Editorial by en_translator


In each query, we take out at most \(K\) balls \((K \leq 5)\) and report the minimum value among the remaining balls.
Here, consider the sequence of \(A_i\) written on all the balls. Notice the first six balls. Then, after balls are taken out, at least one ball remain in the bag. This is because to remove all of them we need to remove six balls, but we are removing at most five balls.

Hence, the problem can be solved by the following approach:

  1. Sort the values \(A_i\) written on the balls in ascending order to find the first six balls.
  2. For each query, check whether each of the six balls were taken out or not. The answer is the first balls that were not removed.

For step 1, there are several ways to retrieve the first six element; one of the easiest ways is to sort pairs \((A_i, i)\). There is also an algorithm to manage the first six elements in the manner of insertion sort; this costs a total of \(\mathrm{O}(N)\) time (while sorting costs \(\mathrm{O}(N \log N)\)), which is advantageous in terms of complexity.

In any case, it can be solved in a total of \(\mathrm{O}(N + Q)\) or \(\mathrm{O}(N \log N + Q)\) time, which is fast enough.

  • Sample code (C++)
#include <algorithm>
#include <iostream>
#include <set>
#include <utility>
#include <vector>
using namespace std;

int main() {
  cin.tie(0)->sync_with_stdio(0);
  int N, Q;
  cin >> N >> Q;
  vector<pair<int, int>> A(N);
  for (int i = 0; i < N; i++) {
    cin >> A[i].first;
    A[i].second = i;
  }
  sort(begin(A), end(A));

  while (Q--) {
    int K;
    cin >> K;
    vector<int> B(K);
    for (auto& b : B) cin >> b;
    for (int i = 0;; i++) {
      if (find(begin(B), end(B), A[i].second + 1) != end(B)) continue;
      cout << A[i].first << "\n";
      break;
    }
  }
}

posted:
last update: