#include <iostream> #include<list> using namespace std; int sameBrands[50001]; int main() { ios_base::sync_with_stdio(false); int bottlesCount; int leftCount; list<int> places_to_move; cin >> bottlesCount >> leftCount; int currentIndex = 0; int result = 0; while(currentIndex < bottlesCount) { int currentBrand; cin >> currentBrand; if(sameBrands[currentBrand] == 0) { if(!places_to_move.empty()) { int place_to_move = places_to_move.back(); result += currentIndex - place_to_move; places_to_move.pop_back(); if(currentIndex < leftCount) { places_to_move.push_front(currentIndex); } } sameBrands[currentBrand]++; } else { if(currentIndex < leftCount) { places_to_move.push_front(currentIndex); } } if(currentIndex >= leftCount - 1 && places_to_move.empty()) { cout << result << "\n"; return 0; } currentIndex++; } cout << "-1\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 | #include <iostream> #include<list> using namespace std; int sameBrands[50001]; int main() { ios_base::sync_with_stdio(false); int bottlesCount; int leftCount; list<int> places_to_move; cin >> bottlesCount >> leftCount; int currentIndex = 0; int result = 0; while(currentIndex < bottlesCount) { int currentBrand; cin >> currentBrand; if(sameBrands[currentBrand] == 0) { if(!places_to_move.empty()) { int place_to_move = places_to_move.back(); result += currentIndex - place_to_move; places_to_move.pop_back(); if(currentIndex < leftCount) { places_to_move.push_front(currentIndex); } } sameBrands[currentBrand]++; } else { if(currentIndex < leftCount) { places_to_move.push_front(currentIndex); } } if(currentIndex >= leftCount - 1 && places_to_move.empty()) { cout << result << "\n"; return 0; } currentIndex++; } cout << "-1\n"; return 0; } |