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
#include <bits/stdc++.h>
using namespace std;

typedef int64_t ll;
typedef uint64_t ull;
typedef unsigned int ui;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<long long> vll;
constexpr ll LINF = 1e18;
constexpr int INF = 1e9;

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

    int n, c;
    int max_wi = 1;
    vector<int> a;
    vector<unordered_set<int>> w;

    cin >> n >> c;
    for (int i = 0; i < n; ++i) {
        int ai, wi;
        cin >> ai >> wi;

        max_wi = max(max_wi, wi);
        if (i == 0 || a.back() != ai) {
            a.push_back(ai);
            w.push_back({});
        }

        w.back().insert(wi);
    }

    ll result = 0;
    ll best_w[max_wi + 1] = {};

    for (size_t i = 0; i < a.size(); ++i) {
        ll best_ai = 0;
        for (int pattern: w[i]) {
            ll score = a[i] + max(result - c, best_w[pattern]);

            best_ai = max(score, best_ai);
            best_w[pattern] = max(score, best_w[pattern]);
        }

        result = max(best_ai, result);
    }

    cout << result << endl;

    return 0;
}