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
#include <algorithm>
#include <cstdio>

#define REP(a, n) for (int a = 0; a<(n); ++a)
#define FOR(a, b, c) for (int a = (b); a<=(c); ++a)

typedef long long LL;

using namespace std;

//////////////

int N, C;

pair<int, int> wie[500000];
LL best[500001], bb, newbb;

int main() {
    scanf("%d%d", &N, &C);
    REP(a, N)
        scanf("%d%d", &wie[a].first, &wie[a].second);
    sort(wie, wie+N);
    N = unique(wie, wie+N)-wie;
    reverse(wie, wie+N);
    int rozm = 600000;
    REP(a, N) {
        if (wie[a].first<rozm)
            bb = newbb;
        rozm = wie[a].first;
        LL res = max(bb-C, best[wie[a].second])+rozm;
        best[wie[a].second] = res;
        newbb = max(newbb, res);
    }
    printf("%lld\n", newbb);
}