C - Σ Editorial by en_translator
Since is large, we cannot naively enumerate and find the sum of those not included in . Instead, we take the following approach:
- Let .
- Enumerate integers between and that occur at least once in , and subtract each of them from .
- Print .
In order to enumerate integers between and that occur at least once in , one has to remove integers or greater from , 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 , and the latter expectedly costs . 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++):
#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;
}
#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: