#include <vector> #include <set> #include <cstdio> #define ll long long using namespace std; ll solve(vector<int>& a, int k) { int n = a.size(); set<int> pastBottles; int j = 0; ll res = 0; for(int i=0;i<k;i++) { if(!pastBottles.insert(a[i]).second) { if(j <= i) { j = i + 1; } while((j < n) && (!pastBottles.insert(a[j]).second)) j++; if(j >= n) { return -1; } res += j - i; } } return res; } int main(int argc, char** argv) { int n, k; scanf("%d%d", &n, &k); vector<int> a(n); for(int i=0;i<n;i++) { scanf("%d",&(a[i])); } ll res = solve(a, k); printf("%lld\n", 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 31 32 33 34 35 36 37 38 39 | #include <vector> #include <set> #include <cstdio> #define ll long long using namespace std; ll solve(vector<int>& a, int k) { int n = a.size(); set<int> pastBottles; int j = 0; ll res = 0; for(int i=0;i<k;i++) { if(!pastBottles.insert(a[i]).second) { if(j <= i) { j = i + 1; } while((j < n) && (!pastBottles.insert(a[j]).second)) j++; if(j >= n) { return -1; } res += j - i; } } return res; } int main(int argc, char** argv) { int n, k; scanf("%d%d", &n, &k); vector<int> a(n); for(int i=0;i<n;i++) { scanf("%d",&(a[i])); } ll res = solve(a, k); printf("%lld\n", res); return 0; } |