#include <iostream> #include <algorithm> using namespace std; int main() { int n = 0; int dlugosc_ciagu = 0; cin >> n >> dlugosc_ciagu; int tablica[n]; int ciag[n]; int wazna[n]; int sumka = 0; for(int i = 0; i < n;i++) { ciag[i] = 0; } for(int i = 0; i < n;i++) { cin >> tablica[i]; if(ciag[tablica[i]-1]==0) { wazna[i] = 1; sumka += 1; } else { wazna[i] = 0; } ciag[tablica[i]-1] = 1; } int wynik = 0; if(dlugosc_ciagu > sumka) { cout << -1; } else { for(int h = 0; h <dlugosc_ciagu;h++) { if(wazna[h]==0) { for(int i = h+1; i < n; i++) { if(wazna[i]==1) { wynik += i - h; wazna[i] = 0; break; } } } } cout << wynik; } 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 | #include <iostream> #include <algorithm> using namespace std; int main() { int n = 0; int dlugosc_ciagu = 0; cin >> n >> dlugosc_ciagu; int tablica[n]; int ciag[n]; int wazna[n]; int sumka = 0; for(int i = 0; i < n;i++) { ciag[i] = 0; } for(int i = 0; i < n;i++) { cin >> tablica[i]; if(ciag[tablica[i]-1]==0) { wazna[i] = 1; sumka += 1; } else { wazna[i] = 0; } ciag[tablica[i]-1] = 1; } int wynik = 0; if(dlugosc_ciagu > sumka) { cout << -1; } else { for(int h = 0; h <dlugosc_ciagu;h++) { if(wazna[h]==0) { for(int i = h+1; i < n; i++) { if(wazna[i]==1) { wynik += i - h; wazna[i] = 0; break; } } } } cout << wynik; } return 0; } |