#include "stdio.h" #include <vector> #include <algorithm> #include <set> using namespace std; int orig[500100]; int des[500100]; int main(){ set<int> s; int n, k; scanf("%d %d", &n, &k); int uniq = 0; for (int i = 0; i < n; i++) { int a; scanf("%d", &a); orig[i] = a; if (s.find(a) == s.end()) { des[i] = uniq; uniq++; } else des[i] = -1; s.insert(a); } /* for (int i = 0; i < n; i++) { printf("%d: %d %d\n", i, orig[i], des[i]); } */ if (uniq < k) { printf("-1\n"); return 0; } long long int sum = 0; int i = 0; int h = 0; while (h < k) { // printf ("i: %d, orig: %d, des: %d, h: %d; k: %d, sum: %lld\n", i, orig[i], des[i], h, k, sum); if (des[i] != -1) { sum += (long long int)(i - des[i]); h++; } i++; } printf("%lld\n", sum); }
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 "stdio.h" #include <vector> #include <algorithm> #include <set> using namespace std; int orig[500100]; int des[500100]; int main(){ set<int> s; int n, k; scanf("%d %d", &n, &k); int uniq = 0; for (int i = 0; i < n; i++) { int a; scanf("%d", &a); orig[i] = a; if (s.find(a) == s.end()) { des[i] = uniq; uniq++; } else des[i] = -1; s.insert(a); } /* for (int i = 0; i < n; i++) { printf("%d: %d %d\n", i, orig[i], des[i]); } */ if (uniq < k) { printf("-1\n"); return 0; } long long int sum = 0; int i = 0; int h = 0; while (h < k) { // printf ("i: %d, orig: %d, des: %d, h: %d; k: %d, sum: %lld\n", i, orig[i], des[i], h, k, sum); if (des[i] != -1) { sum += (long long int)(i - des[i]); h++; } i++; } printf("%lld\n", sum); } |