#include <iostream> #include <vector> #include <set> #include <algorithm> struct foo { std::size_t count; std::set<std::size_t> pos; }; long solution(std::vector<int>& data, std::size_t k) { std::unordered_map<int, foo> positions; std::size_t idx = 0; for(auto b : data) { auto& [count, pos] = positions[b]; ++count; pos.insert(idx++); } if(k > positions.size()) { return -1; } std::set<std::size_t> uniq_pos; for(auto& [key, f] : positions) { auto& [c, pos] = f; uniq_pos.insert(*pos.begin()); } long moves = 0; auto next_pos = uniq_pos.begin(); for(idx = 0; idx < k; ++idx) { moves += *next_pos - idx; next_pos = std::next(next_pos); } return moves; } int main() { std::vector<int> vec; std::size_t bottles, k; std::cin >> bottles >> k; vec.reserve(bottles); int buff; while(bottles--) { std::cin >> buff; vec.push_back(buff); } std::cout << solution(vec, k) << '\n'; return 0; }
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 | #include <iostream> #include <vector> #include <set> #include <algorithm> struct foo { std::size_t count; std::set<std::size_t> pos; }; long solution(std::vector<int>& data, std::size_t k) { std::unordered_map<int, foo> positions; std::size_t idx = 0; for(auto b : data) { auto& [count, pos] = positions[b]; ++count; pos.insert(idx++); } if(k > positions.size()) { return -1; } std::set<std::size_t> uniq_pos; for(auto& [key, f] : positions) { auto& [c, pos] = f; uniq_pos.insert(*pos.begin()); } long moves = 0; auto next_pos = uniq_pos.begin(); for(idx = 0; idx < k; ++idx) { moves += *next_pos - idx; next_pos = std::next(next_pos); } return moves; } int main() { std::vector<int> vec; std::size_t bottles, k; std::cin >> bottles >> k; vec.reserve(bottles); int buff; while(bottles--) { std::cin >> buff; vec.push_back(buff); } std::cout << solution(vec, k) << '\n'; return 0; } |