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 <bits/stdc++.h>
using namespace std;
#define st first
#define nd second
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define BOOST ios_base::sync_with_stdio(0), cin.tie(0)
typedef long long ll;
typedef long double ld;
typedef pair<int, int> ii;

const int N = 5e5 + 5;
ll dp[N];

int main(){
	BOOST;
	int n, c; cin >> n >> c;
	vector<ii> dat(n);
	for(int i=0; i<n; i++){
		cin >> dat[i].st >> dat[i].nd;
	}
	reverse(all(dat));
	for(int i=0; i<n;){
		vector<pair<ll, ll>> upd;
		for(int j=i; j<n && dat[j].st == dat[i].st; j++){
			upd.pb({dat[j].nd, max(dp[dat[j].nd], dp[0] - c) + dat[j].st});
		}
		for(auto it : upd){
			dp[it.st] = max(dp[it.st], it.nd);
			dp[0] = max(dp[0], it.nd);
		}
		i += upd.size();
	}
	cout << dp[0] << "\n";
}