Don't force a
class
where a function is perfectly fine.The namespace
std
is not designed for wholesale importation, see "Why is "using namespace std" considered bad practice? " for more detail.Identifiers starting with an underscore followed by an uppercase letter are reserved.
Input is generally unreliable. But you don't test for error at all.
Always recomputing the current result from first principles, instead of just updating it, is a waste of time.
You should probably follow the requested output-Format...
You know that
int
inunsigned int
is implicit?In C++ and C99+,
return 0;
is implicit formain()
.I wonder why you sometimes surround binary operators with space, and sometimes don't.
Having over-long lines is very cumbersome to read. Admittedly, you need not make a hard cut at 79 nowadays.
As it is an interview question, one should verify that one should really use a Set, meaning that repeated elements have no effect, aside from causing an additional output.
As it is an interview question, one should verify that, contrary to the example, the inputs might not be sorted.
#include <iostream>
#include <set>
#include <cstdlib>
int main() {
unsigned n, m, x;
std::cin >> n >> m;
if (!std::cin || !n) {
std::cerr << "Bad Input!\n";
return EXIT_FAILURE;
}
std::set nums{ 0u, n + 1};
auto r = 0ULL;
while (--m) {
std::cin >> x;
if (!std::cin || x < 1 || x > n) {
std::cerr << "Bad Input!\n";
return EXIT_FAILURE;
}
auto [iter, created] = nums.insert(x);
if (created)
r += 2 * x;
std::cout << r << '\n';
}
}
- 19.9k
- 1
- 32
- 65