#include <iostream>
#include <array>
#include <algorithm>
using std::size_t;
template <typename T, size_t N>
class MyArray : std::array<T, N>
{
public:
constexpr void resize(size_t newSize) noexcept
{
_size = newSize;
}
constexpr typename std::array<T, N>::const_iterator cend() const noexcept
{
return std::array<T, N>::cbegin() + _size;
}
using std::array<T, N>::operator[];
using std::array<T, N>::cbegin;
private:
size_t _size{0};
};
int n, // number of bottles 1..500 000
k; // prefix length 1..n
MyArray<int, 500010> bottles{}; // number of the ith bottle
std::array<bool, 500010> alreadySeen; // set of already seen bottles
long long int sum = 0; // number of moves needed to bring the k different bottles to the beginning of the array
int main()
{
std::ios::sync_with_stdio(false);
std::cin >> n >> k;
bottles.resize(std::size_t(n));
for (int i = 0; i < n; i++)
std::cin >> bottles[size_t(i)];
auto NotInSet = [](int bottleNumber){ return !alreadySeen[size_t(bottleNumber)]; };
auto current = bottles.cbegin();
for (int i = 0; i < k; i++)
{
current = std::find_if(current, bottles.cend(), NotInSet);
if (current == bottles.cend())
{
std::cout << "-1\n";
return 0;
}
auto const pos = current - bottles.cbegin();
sum += (pos - i);
alreadySeen[size_t(*current)] = true;
current++;
}
std::cout << sum << '\n';
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | #include <iostream> #include <array> #include <algorithm> using std::size_t; template <typename T, size_t N> class MyArray : std::array<T, N> { public: constexpr void resize(size_t newSize) noexcept { _size = newSize; } constexpr typename std::array<T, N>::const_iterator cend() const noexcept { return std::array<T, N>::cbegin() + _size; } using std::array<T, N>::operator[]; using std::array<T, N>::cbegin; private: size_t _size{0}; }; int n, // number of bottles 1..500 000 k; // prefix length 1..n MyArray<int, 500010> bottles{}; // number of the ith bottle std::array<bool, 500010> alreadySeen; // set of already seen bottles long long int sum = 0; // number of moves needed to bring the k different bottles to the beginning of the array int main() { std::ios::sync_with_stdio(false); std::cin >> n >> k; bottles.resize(std::size_t(n)); for (int i = 0; i < n; i++) std::cin >> bottles[size_t(i)]; auto NotInSet = [](int bottleNumber){ return !alreadySeen[size_t(bottleNumber)]; }; auto current = bottles.cbegin(); for (int i = 0; i < k; i++) { current = std::find_if(current, bottles.cend(), NotInSet); if (current == bottles.cend()) { std::cout << "-1\n"; return 0; } auto const pos = current - bottles.cbegin(); sum += (pos - i); alreadySeen[size_t(*current)] = true; current++; } std::cout << sum << '\n'; } |
English