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
#include <bits/stdc++.h>
#define ll long long
#define range(i, n) for (int i = 0; i < n; i++)

using namespace std;

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

    ll n, c;
    cin >> n >> c;
    map<int, set<ll>> klocki;
    range(i, n) {
        int a, w;
        cin >> a >> w;
        w--;
        klocki[-a].insert(w);
    }
    ll score = 0;
    vector<ll> wzorki_scores(500000, 0);
    for (auto it = klocki.begin(); it != klocki.end(); it++) {
        const ll wielk = -(it->first);
        ll newBest = score;
        for (auto &x : it->second) {
            ll res = max(score + wielk - c, wzorki_scores[x] + wielk);
            wzorki_scores[x] = res;
            newBest = max(newBest, res);
        }
        score = newBest;
    }
    cout << score << "\n";
}