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
#include <iostream>
#include <vector> 
#include <algorithm>
#include <map>
#include <utility>

int main() {
    int n, k, x;
    std::ios_base::sync_with_stdio(0);
    std::cin >> n >> k;
    std::map <int, int> bottleLoc;
    std::vector<std::pair<int, int> > results;
    for(int i = 0; i < n; ++i) {
        std::cin >> x;
        bottleLoc.insert(std::make_pair(x, i));
    }

    if(bottleLoc.size() < k) {
        std::cout << -1;
    } else {
        for (auto it = bottleLoc.begin(); it != bottleLoc.end(); ++it) {
            results.push_back(std::make_pair((*it).second, (*it).first));
        }
        std::sort(results.begin(), results.end());
        long long jump = 1, sum = 0;
        for(int i = k - 2; i >= 0; --i) {
            sum += (results[i + 1].first - results[i].first - 1) * jump;
            jump++;
        }
        std::cout << sum;
    }
}