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
55
56
57
58
59
60
61
62
63
64
65
#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

#define pii pair<ll, ll>
#define st first
#define nd second
#define pb push_back

const int MAXW = 500 * 1000;
const int MAXN = 500 * 1000;

multiset<ll> ms;
pii a[MAXN];
ll rekordkolor[MAXW + 1];
ll dp[MAXN];
vector<pair<ll, pii>> dozmiany;

int main () {
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    for (int i = 1; i <= MAXW + 20; i ++) {
        ms.insert(0LL);
    }

    int n;
    ll c;
    cin >> n >> c;
    for (int i = 0; i < n; i ++) {
        cin >> a[i].st >> a[i].nd;
    }

    reverse(a, a + n);
    ll poprzedni = -1;
    for (int i = 0; i < n; i ++) {
        if (a[i].st != poprzedni) {
            for (auto x : dozmiany) {
                if (x.nd.nd > rekordkolor[x.st]) {
                    rekordkolor[x.st] = x.nd.nd;
                    ms.erase(ms.find(x.nd.st));
                    ms.insert(x.nd.nd);
                }
            }
            dozmiany.clear();
        }


        ll tegokoloru = rekordkolor[a[i].nd];
        ms.erase(ms.find(tegokoloru));
        dp[i] = max(tegokoloru + a[i].st, *ms.rbegin() + a[i].st - c);
        dozmiany.pb({a[i].nd, {rekordkolor[a[i].nd], max(rekordkolor[a[i].nd], dp[i])}});
        ms.insert(tegokoloru);

        poprzedni = a[i].st;
    }

    ll wyn = 0;
    for (int i = 0; i < n; i ++) {
        wyn = max(wyn, dp[i]);
    }

    cout << wyn << "\n";

    return 0;
}