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

using namespace std;

typedef long long LL;
constexpr int M = 500000;

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

    int n, c;
    cin >> n >> c;

    vector<vector<int>> blocks(M + 1);
    vector<LL> best(M + 1);

    int a, w;
    for (int i = 0; i < n; ++i)
    {
        cin >> a >> w;
        blocks[a].push_back(w);
    }

    LL res = 0;
    LL tmp = 0;
    for (int a = M; a; --a)
    {
        sort(blocks[a].begin(), blocks[a].end());
        blocks[a].erase(unique(blocks[a].begin(), blocks[a].end()), blocks[a].end());

        for (int w : blocks[a]) tmp = max(tmp, max(res + a - c, best[w] + a));
        for (int w : blocks[a]) best[w] = max(best[w] + a, res + a - c);

        res = max(res, tmp);
    }
    cout << res;
}