#include<bits/stdc++.h> #define vi vector<int> #define vvi vector<vi> #define pii pair<int, int> #define pll pair<ll, ll> #define vii vector<pii> #define vb vector<bool> #define vvb vector<vb> #define vl vector<ll> #define endl '\n' #define turbo ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); #define pb push_back #define ll long long #define f first #define s second using namespace std; int n, k; vi v; set<int> se, ind; int main() { turbo cin >> n >> k; v = vi(n); for(auto &it : v) cin >> it; for(int i = 0; i < n; i++) if(se.find(v[i]) == se.end()) { se.insert(v[i]); if(i >= k) ind.insert(i); } ll res = 0; for(int i = 0; i < k; i++) { if(se.find(v[i]) != se.end()) se.erase(v[i]); else { if(ind.empty()) { res = -1; break; } else { res += ((*ind.begin())-i); ind.erase(ind.begin()); } } } cout << res << endl; }
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 | #include<bits/stdc++.h> #define vi vector<int> #define vvi vector<vi> #define pii pair<int, int> #define pll pair<ll, ll> #define vii vector<pii> #define vb vector<bool> #define vvb vector<vb> #define vl vector<ll> #define endl '\n' #define turbo ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); #define pb push_back #define ll long long #define f first #define s second using namespace std; int n, k; vi v; set<int> se, ind; int main() { turbo cin >> n >> k; v = vi(n); for(auto &it : v) cin >> it; for(int i = 0; i < n; i++) if(se.find(v[i]) == se.end()) { se.insert(v[i]); if(i >= k) ind.insert(i); } ll res = 0; for(int i = 0; i < k; i++) { if(se.find(v[i]) != se.end()) se.erase(v[i]); else { if(ind.empty()) { res = -1; break; } else { res += ((*ind.begin())-i); ind.erase(ind.begin()); } } } cout << res << endl; } |