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

const int MAX = 500000;
int N;
long long C;
long long dp[MAX];
int last_heights[MAX];
long long dp_max_current;
long long dp_max_previous;
int last_height;

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

	cin >> N >> C;
	for(int i = 0; i < MAX; i++){
		dp[i] = 0;
		last_heights[i] = -1;
	}

	dp_max_current = 0;
	dp_max_previous = 0;
	last_height = -1;

	long long h;
	int c;
	for(int i = 0; i < N; i++){
		cin >> h >> c;
		c--;
		
		if(h > last_height){
			last_height = h;
			dp_max_previous = max(dp_max_current, dp_max_previous);
			dp_max_current = 0;
		}

		if(last_heights[c] != h){
			last_heights[c] = h;

			dp[c] = h + max(dp[c], dp_max_previous - C); 
		}

		dp_max_current = max(dp_max_current, dp[c]);
	}

	cout << max(dp_max_previous, dp_max_current) << endl;
}