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
// Online C++ compiler to run C++ program online
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>

int main() {
    long long n, c;
    std::cin >> n >> c;
    std::vector<std::pair<long long, long long>> cubes;
    std::map<long long, std::vector<long long>> cubesByStyle;
    std::map<long long, long long> sums;

    for (long long i = 0; i < n; i++)
    {
        long long t1, t2;
        std::cin >> t1 >> t2;
        cubes.push_back(std::make_pair(t1, t2));

        if (cubesByStyle.count(t2))
        {
            cubesByStyle.at(t2).push_back(t1);
            sums.at(t2) = sums.at(t2) + t1;
        }
        else
        {
            cubesByStyle.insert(std::make_pair(t2, std::vector<long long>{t1}));
            sums.insert(std::make_pair(t2, t1));
        }
    }

    long long maxScoreKey = std::max_element(sums.begin(), sums.end(), [](const std::pair<long long, long long>& a, const std::pair<long long, long long>& b)->bool { return a.second < b.second; })->first;
    long long score = sums[maxScoreKey];

    bool previousReplaced = true;

    for (std::vector<std::pair<long long, long long>>::iterator i = cubes.begin(); i != cubes.end(); i++)
    {
        if (i->second == maxScoreKey || count(cubesByStyle[maxScoreKey].begin(), cubesByStyle[maxScoreKey].end(), i->first))
        {
            previousReplaced = false;
            continue;
        }

        long long sum = i->first - (previousReplaced || i->first > cubesByStyle[maxScoreKey].back() ? 1 : 2) * c;
        if (sum > 0)
        {
            score += sum;
            previousReplaced = true;
        }
    }

    std::cout << score;

    return 0;
}