#include <iostream> using namespace std; int main () { ios_base::sync_with_stdio(0); cin.tie(0); int n, k, bottle, kinds; long long time; kinds = 0; time = 0; cin >> n >> k; int * bottles; // values: [1; n] int * position; //nearest position [0; n-1] for bottle i bool * is_selected; //is bottle i [1; n] selected; int * selected; bottles = new int[n]; position = new int[n + 1]; is_selected = new bool[n + 1]; selected = new int[k]; for (int i = 0; i <=n; ++i) { position[i] = -1; is_selected[i] = false; } for (int i = 0; i < k; ++i) { selected[i] = -1; } for (int i = 0; i < n; ++i) { cin >> bottle; bottles[i] = bottle; if (position[bottle] < 0 ) { // new kind of bottle position[bottle] = i; ++kinds; if (i < k) { is_selected[bottle] = true; selected[i] = bottle; } } } if (kinds < k) { cout << -1; return 0; } int bad_bottle; for (int i = 0; i < k; ++i) { if (selected[i] < 0) { bad_bottle = bottles[i]; for (int j = i + 1; j < n; ++j) { if (! is_selected[bottles[j]]) { is_selected[bottles[j]] = true; selected[i] = bottles[j]; time += position[bottles[j]] - i; // fixing // for (int k = j; k > i + 1; --k) { // bottles[k] = bottles[k - 1]; // position[bottles[k]] = k; // } // bottles[i + 1] = bad_bottle; // position[bottles[i + 1]] = i + 1; // bottles[i] = selected[i]; // position[bottles[i]] = i; // next i break; } } } } cout << time; 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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | #include <iostream> using namespace std; int main () { ios_base::sync_with_stdio(0); cin.tie(0); int n, k, bottle, kinds; long long time; kinds = 0; time = 0; cin >> n >> k; int * bottles; // values: [1; n] int * position; //nearest position [0; n-1] for bottle i bool * is_selected; //is bottle i [1; n] selected; int * selected; bottles = new int[n]; position = new int[n + 1]; is_selected = new bool[n + 1]; selected = new int[k]; for (int i = 0; i <=n; ++i) { position[i] = -1; is_selected[i] = false; } for (int i = 0; i < k; ++i) { selected[i] = -1; } for (int i = 0; i < n; ++i) { cin >> bottle; bottles[i] = bottle; if (position[bottle] < 0 ) { // new kind of bottle position[bottle] = i; ++kinds; if (i < k) { is_selected[bottle] = true; selected[i] = bottle; } } } if (kinds < k) { cout << -1; return 0; } int bad_bottle; for (int i = 0; i < k; ++i) { if (selected[i] < 0) { bad_bottle = bottles[i]; for (int j = i + 1; j < n; ++j) { if (! is_selected[bottles[j]]) { is_selected[bottles[j]] = true; selected[i] = bottles[j]; time += position[bottles[j]] - i; // fixing // for (int k = j; k > i + 1; --k) { // bottles[k] = bottles[k - 1]; // position[bottles[k]] = k; // } // bottles[i + 1] = bad_bottle; // position[bottles[i + 1]] = i + 1; // bottles[i] = selected[i]; // position[bottles[i]] = i; // next i break; } } } } cout << time; return 0; } |