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<iostream>
#include<algorithm>
#include<map>
using namespace std;

const int MAXW = 500002;

int main() {
	long long n, c;
	cin >> n >> c;
	
	long long w[MAXW];
	long long last_ai[MAXW]; 
	
	for(int i = 0; i < MAXW; i++)
		w[i] = last_ai[i] = 0;
	
	long long best = 0;
	long long best2 = 0;
	int bok2 = 0;
	
	
	for(int i = 0; i < n; i++) {
		int ai, wi;
		cin >> ai >> wi;
		
		
		if(ai > bok2) {
			best = best2;
			bok2 = ai;
		}
		
		if(last_ai[wi] == ai)
			continue;
		
		long long nowe_h = w[wi] + ai;
		if(best + ai - c > nowe_h)
			nowe_h = best + ai - c;
		
		w[wi] = nowe_h;
		last_ai[wi] = ai;
		
		
		if(best2 < nowe_h)
			best2 = nowe_h;		
	}
	
	cout << best2 << endl;
	
	return 0;
}