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

using namespace std;
typedef long long ll;

int main(){
	
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	
	int n, c;
	cin >> n >> c;
	
	int mx_c = 0, mx_h = 0;
	vector<pair<int, int> > pre(n);
	for(int i = 0 ; i < n; ++i){
		cin >> pre[i].second >> pre[i].first;
		mx_c = max(mx_c, pre[i].first);
		mx_h = max(mx_h, pre[i].second);
	}
	
	sort(pre.begin(), pre.end());
	vector<pair<int, int> > t;
	
	t.push_back({pre[0].second, pre[0].first});
	for(int i = 1; i < n; ++i){
		if(pre[i] == pre[i - 1]) continue;
		t.push_back({pre[i].second, pre[i].first});
	}
	sort(t.begin(), t.end());
		
	ll tmp = 0;
	ll res = 0;
	
	vector<ll> resColor(mx_c + 1, 0);	
	vector<ll> dp(n + 1);
	dp[n] = 0;
	for(int i = (int)t.size() - 1; i >= 1; --i){
		//~ cout << " kolor " << t[i].second << " wys " << t[i].first << endl;
		//~ cout << " wyn_suf " << res << " wyn_kol " << resColor[t[i].second] << endl;
		dp[i] = max((ll)0, max(res - c, resColor[t[i].second]) + t[i].first);
		tmp = max(tmp, dp[i]);
		
		if(t[i - 1].first != t[i].first){
			res = max(res, tmp);
			tmp = 0;
		}
		resColor[t[i].second] = max(resColor[t[i].second], dp[i]);
		dp[i] = max(dp[i], dp[i + 1]);
		//~ cout << " DP -- > " << dp[i] << endl;
		//~ cout << endl;
	}
	dp[0] = max((ll)0, max(res - c, resColor[t[0].second]) + t[0].first);
	dp[0] = max(dp[0], dp[1]);
	printf("%lld\n", dp[0]);
	return 0;
}