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

const int MAXN = 5e5 + 7, nTree = (1 << 19);

typedef long long ll;

ll T[nTree * 2];

void update(int pos, ll val) {
	pos += nTree;
	T[pos] = max(T[pos], val);
	pos /= 2;
	while (pos) {
		T[pos] = max(T[pos * 2], T[pos * 2 + 1]);
		pos /= 2;
	}
}

ll query(int l, int r) {
	if (l > r) return 0;
	l += nTree, r += nTree;
	ll res = T[l];
	if (l < r) res = max(res, T[r]);
	while (l < r - 1) {
		if (l % 2 == 0) res = max(res, T[l + 1]);
		if (r % 2 == 1) res = max(res, T[r - 1]);
		l /= 2, r /= 2;
	}
	return res;
}

vector<int> arr[MAXN];

int main() {
	ios_base::sync_with_stdio(0);
	int n, c; cin >> n >> c;
	for (int i = 0; i < n; ++i) {
		int a, w; cin >> a >> w;
		arr[a].push_back(w);
	}
	for (int i = MAXN - 1; i >= 1; --i) {
		vector<pair<int, ll> > maxis;
		for (int &w : arr[i]) {
			ll maxi = query(w, w) + i;
			maxi = max(maxi, query(1, nTree - 1) + i - c);
			maxis.push_back({w, maxi});
		}
		for (auto &p : maxis) {
			update(p.first, p.second);
		}
	}
	cout << query(1, nTree - 1) << "\n";
}