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

struct node {
    int64_t prev_score;
    int64_t next_score = 0;
    int32_t next_a = 0;

    int64_t get(int32_t a) {
        if (next_a < a) {
            prev_score = next_score;
        }
        return prev_score;
    }
    void improve(int32_t a, int64_t score) {
        get(a);
        if (next_score < score) {
            next_a = a;
            next_score = score;
        }
    }
};

int main() {
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);

    int32_t n, c;
    std::cin >> n >> c;

    std::vector<node> v(500001);
    for (int32_t i = 0; i < n; ++i) {
        int32_t a, w;
        std::cin >> a >> w;

        auto diff = v[0].get(a) + a - c;
        auto same = v[w].get(a) + a;
        auto res = std::max(diff, same);

        v[0].improve(a, res);
        v[w].improve(a, res);
    }

    std::cout << v[0].get(500001) << "\n";
}