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

int main() {
    int n;
    int64_t c;
    std::cin >> n >> c;

    std::map<int, int64_t> bestBefore;
    std::map<int, int64_t> bestNow;
    int64_t bestOverall = 0;

    int previous = -1;
    for (int i = 0; i < n; ++i) {
        int64_t ai;
        int64_t wi;
        std::cin >> ai >> wi;
        if (previous != ai) {
            previous = ai;

            for (auto const &[_, b] : bestNow) {
                bestOverall = std::max(bestOverall, b);
            }

            for (auto [k, v] : bestNow) {
                bestBefore[k] = std::max(bestBefore[k], v);
            }
            bestNow.clear();
        }

        bestNow[wi] = std::max({ai,
                                ai + bestOverall - c,
                                ai + bestBefore[wi]});
    }

    for (auto const &[_, b] : bestNow) {
        bestOverall = std::max(bestOverall, b);
    }

    std::cout << bestOverall << std::endl;

    return 0;
}