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
58
59
60
61
62
63
64
65
66
67
68
#include <bits/stdc++.h>

#define ll long long
#define fors(u, n, s) for(ll u = (s); u < (n); u++)
#define foru(u, n) fors(u, n, 0)
#define f first
#define s second
#define vec vector
#define pb push_back
#define ir(a, b, x) (((a) <= (x)) && ((x) <= (b)))

using namespace std;

const int N = 5e5 + 100;
int n, c;

unordered_set<ll> colors[N];
ll  heights[N];

ll dp[N];
ll  max_so_far = 0;

int main() {
	cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0);

	cin >> n >> c;

	int m = -1;
	int prev_a = -1;
	foru(_i, n) {
		int a, w; cin >> a >> w;
		if(a != prev_a) {
			m ++;
			prev_a = a;
		}
		colors[m].insert(w);
		heights[m] = a;
	}
	m ++;

	// cout << m << endl;
	// foru(i, m) {
	// 	cout << "height " << heights[i] << " elements: ";
	// 	for(auto j : colors[i]) cout << j << " ";
	// 	cout << endl;
	// }
	// return 0;

	for(int i = m-1; i >= 0; i--){
		ll new_max = max_so_far;
		
		for (auto col : colors[i]) {
			ll old_val = dp[col];
		
			dp[col] = max(dp[col], heights[i]); // start from zero
			dp[col] = max(dp[col], old_val + heights[i]); // add to mathing color
			dp[col] = max(dp[col], max_so_far + heights[i] - c); // add to different color

			new_max = max(new_max, dp[col]);
		}

		max_so_far = new_max;
	}

	cout << max_so_far;

    return 0;
}