#include <iostream> #include <list> #include <set> #include <bitset> #define MAX 500001 using namespace std; typedef long long ll; int main() { ios_base::sync_with_stdio(false); ll a, n, k; cin >> n >> k; list<ll> nums; set<ll> unique; bitset<MAX> seen; while (n-- > 0) { cin >> a; unique.insert(a); nums.push_back(a); } if (unique.size() < k) { cout << -1; return 0; } ll pos = 0; ll dist = 0; ll sum = 0; auto head = nums.begin(); auto tail = nums.begin(); while (pos < k) { if (seen.test(*head)) { // we need to insert something here ;) while (seen.test(*tail)) { tail++; dist++; } head = nums.insert(head, *tail); tail = nums.erase(tail); sum += dist; dist++; } else { seen.set(*head, true); head++; pos++; dist--; } } cout << sum; 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 <list> #include <set> #include <bitset> #define MAX 500001 using namespace std; typedef long long ll; int main() { ios_base::sync_with_stdio(false); ll a, n, k; cin >> n >> k; list<ll> nums; set<ll> unique; bitset<MAX> seen; while (n-- > 0) { cin >> a; unique.insert(a); nums.push_back(a); } if (unique.size() < k) { cout << -1; return 0; } ll pos = 0; ll dist = 0; ll sum = 0; auto head = nums.begin(); auto tail = nums.begin(); while (pos < k) { if (seen.test(*head)) { // we need to insert something here ;) while (seen.test(*tail)) { tail++; dist++; } head = nums.insert(head, *tail); tail = nums.erase(tail); sum += dist; dist++; } else { seen.set(*head, true); head++; pos++; dist--; } } cout << sum; return 0; } |