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
#include <bits/stdc++.h>
#define e using u=ostream;template<class a,class b>u&operator<<(u&o,pair<a,b>&x)
using namespace std;e;u&operator<<(u&o,string&s){return o<<s.c_str();}template<
class t>auto operator<<(u&o,t&x)->decltype(x.end(),o){o<<'{';int i=2;for(auto y:
x)o<<", "+i<<y,i=0;return o<<'}';}e{return o<<'('<<x.first<<", "<<x.second<<')';}
#ifdef DEBUG
#define LOG(x...)cerr<<"["#x"]: ",[](auto...$){((cerr<<$<<"; "),...)<<'\n';}(x)
#else
#define LOG(...)
#endif
#define ff first
#define ss second
#define ll long long

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n, c;
    cin >> n >> c;
	vector <pair <ll, int> > klocki(n); // size kolor
	for (int i = n-1; i >= 0; i--) {
		cin >> klocki[i].ff >> klocki[i].ss;
	}
	int maxkolor = 500001;
	vector <ll> dp(n);
	vector <ll> bestkolor(maxkolor, -1);
	ll best = -1;
	ll res = 0;
		
	int i = n-1;
	while (i >= 0) {
		vector <int> samesize;
		samesize.emplace_back(i);
		while (i > 0 && klocki[i].ff == klocki[i-1].ff) {
			samesize.emplace_back(--i);
		}
		i--;
		for (auto klocek : samesize) {
			dp[klocek] = klocki[klocek].ff + 
				max({(ll)0, bestkolor[klocki[klocek].ss], best-c});
			res = max(res, dp[klocek]);
		}
		for (auto klocek : samesize) {
			best = max(best, dp[klocek]);
			bestkolor[klocki[klocek].ss] = max(bestkolor[klocki[klocek].ss], dp[klocek]);
		}
	}
	cout << res << "\n";


}