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

const int N = 1e6 + 5;

#define st first
#define nd second

typedef pair<int,int> pun;
typedef long long ll;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n, c;
	cin >> n >> c;
	vector<pair<int,int>> v;
	for (int i = 0; i < n; i ++) {
		int a, b;
		cin >> a >> b;	
		v.emplace_back(a, b);
	}
	sort(v.begin(), v.end());
	// Move all duplicates to last of vector
    	auto it = unique(v.begin(), v.end());

    	// Remove all duplicates
    	v.erase(it, v.end());
	reverse(v.begin(), v.end());
	long long best = 0;
	ll new_best = 0;
	long long last = 0;
	map<int, ll> wbest;
	for (auto p : v) {
		if (p.first != last) {
			best = new_best;
			last = p.first;
		}
		int score = p.st;
		int w = p.nd;
		ll res = max(wbest[w] + score, best + score - c);
		new_best = max(new_best, res);
		wbest[w] = max(wbest[w], res);
	}
	cout << new_best;
}