Official

C - Σ Editorial by en_translator


Since KK is large, we cannot naively enumerate 1,2,,K1,2,\dots,K and find the sum of those not included in AA. Instead, we take the following approach:

  1. Let ans=1+2++K=K(K+1)2\mathrm{ans}=1+2+\dots+K=\frac{K(K+1)}{2}.
  2. Enumerate integers between 11 and KK that occur at least once in AA, and subtract each of them from ans\mathrm{ans}.
  3. Print ans\mathrm{ans}.

In order to enumerate integers between 11 and KK that occur at least once in AA, one has to remove integers (K+1)(K+1) or greater from AA, and remove duplicates. There are multiple way to remove duplicates, but for example, one can use a data structure that can manage a set, such as std::set in C++ or set in Python. These data structures enable us to maintain elements without duplicates (they may support other features too). More specifically, some of them such as std::set in C++ internally uses balanced binary search tree, while others such as std::unordered_set in C++ and set in Python employs hash; these two kinds have different computational complexity and features. In this problem, both can be used; the former costs a total of O(NlogN)O(N\log N), and the latter expectedly costs O(N)O(N). For the latter case, beware that collision of hashes may worsen the complexity. In the sample code below, std::set in C++ is used.

Sample code (C++):

Copy
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. using ll = long long;
  4. int main() {
  5. int n, k;
  6. cin >> n >> k;
  7. set<int> st;
  8. for (int i = 0; i < n; i++) {
  9. int a;
  10. cin >> a;
  11. if (a <= k) st.insert(a);
  12. }
  13. ll ans = (ll) k * (k + 1) / 2;
  14. for (int i: st) ans -= i;
  15. cout << ans << endl;
  16. }
#include <bits/stdc++.h>

using namespace std;

using ll = long long;

int main() {
    int n, k;
    cin >> n >> k;
    set<int> st;
    for (int i = 0; i < n; i++) {
        int a;
        cin >> a;
        if (a <= k) st.insert(a);
    }
    ll ans = (ll) k * (k + 1) / 2;
    for (int i: st) ans -= i;
    cout << ans << endl;
}

posted:
last update:



2025-03-14 (Fri)
06:35:59 +00:00