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

const int MAX_N = 5e5 + 5;
const long long inf = LLONG_MAX;
vector<pair<int, int>> blocks(MAX_N);
vector<long long> same_pattern(MAX_N, -inf);
long long best = -inf, ans;
int n, c;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    cin >> n >> c;

    for(int i = 0; i < n; i++) {
        cin >> blocks[i].first >> blocks[i].second;
    }

    sort(blocks.begin(), blocks.end(), greater<pair<int, int>>());

    int i = 0;

    while(i < n) {
        vector<pair<int, int>> group;
        int b = blocks[i].first;

        while(i < n && blocks[i].first == b) {
            group.push_back(blocks[i]);
            i++;
        }

        vector<long long> dp(group.size());

        for(int j = 0; j < group.size(); j++) {
            int p = group[j].second;

            long long diff_p = (best == -inf? -inf : best - c);
            dp[j] = b + max({0LL, same_pattern[p], diff_p});

            ans = max(ans, dp[j]);
        }

        for(int j = 0; j < group.size(); j++) {
            int p = group[j].second;
            same_pattern[p] = max(same_pattern[p], dp[j]);
            best = max(best, dp[j]);
        }
    }

    cout << ans << '\n';
}