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
#include<iostream>
#include<stdio.h>
#include<set>
#include<vector>
#include<algorithm>

using namespace std;

int main() {
	std::ios::sync_with_stdio(false);
	std::cin.tie(NULL);
	
	int n;
	long long c;
	cin >> n >> c;
	
	vector<set<long long> > colors(500001);
	
	for (int i = 0; i < n; i++) {
		int a, w;
		cin >> a >> w;
		colors[a].insert(w);
	}
	
	long long mx = 0LL;
	vector<long long> max_lc(500001, 0LL);
	
	for (int h = 500000; h > 0; h--) {
		if (colors[h].empty()) {
			continue;
		}
		
		long long H = (long long) h;
		set<long long>::iterator itr;
		
		long long old_max = mx;
		for (itr = colors[h].begin(); itr != colors[h].end(); itr++) {
			int color = *itr;
			long long if_matching = H + max_lc[color];
			long long if_not_matching = H + mx - c;
			long long result = max(if_matching, if_not_matching);
			if (result > old_max) {
				old_max = result;
			}
			max_lc[color] = result;
		}
		
		mx = old_max;
	}
	
	cout << mx;
}