#include <iostream> #include <algorithm> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long n, k, tab[500000], a, res = 0, diff = 0; cin >> n >> k; for (int i = 0; i < n; ++i) tab[i] = 500000; for (int i = 0; i < n; ++i) { cin >> a; if (tab[a-1] == 500000) diff++; if (i < tab[a-1]) tab[a-1] = i; } if (diff < k) { cout << -1; return 0; } sort(tab, tab+n); for (int i = 0; i < k; ++i) { res += tab[i]; } res -= (k*(k-1)/2); cout << res; 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 | #include <iostream> #include <algorithm> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long n, k, tab[500000], a, res = 0, diff = 0; cin >> n >> k; for (int i = 0; i < n; ++i) tab[i] = 500000; for (int i = 0; i < n; ++i) { cin >> a; if (tab[a-1] == 500000) diff++; if (i < tab[a-1]) tab[a-1] = i; } if (diff < k) { cout << -1; return 0; } sort(tab, tab+n); for (int i = 0; i < k; ++i) { res += tab[i]; } res -= (k*(k-1)/2); cout << res; return 0; } |