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
69
70
71
72
73
74
75
76
#include<bits/stdc++.h>

using namespace std;	

struct gowno {
	long long wys;
	int kol;
	long long x;
};	

const int base=1<<19;
long long tree[base*2];
queue<gowno> Q;

long long przedzial(int a, int b) {
	long long wyn=0;
	a+=base-1;
	b+=base+1;
	while(a>>1!=b>>1) {
		if(!(a&1)) {
			wyn=max(tree[a+1], wyn);
		}	
		if(b&1) {
			wyn=max(wyn, tree[b-1]);
		}	
		a>>=1;
		b>>=1;
	}	
	return wyn;
}	

void dodaj(int a, long long b) {
	a+=base;
	if(b<=tree[a]) {
		return;
	}
	tree[a]=b;
	a/=2;
	while(a) {
		tree[a]=max(tree[a*2], tree[a*2+1]);
		a>>=1;
	}	
}	

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int n, w;
	long long c, a, kolor, wyn, teraz, WYN=0;
	cin >> n >> c;
	for(int i=1; i<=n; i++) {
		cin >> a >> w;
		while(Q.size()>0 && Q.front().wys<a) {
			kolor=Q.front().kol;
			wyn=Q.front().x;
			dodaj(kolor, wyn);	
			Q.pop();
		}	
		teraz=a;
		teraz=max(teraz, tree[w+base]+a);
		//cout << teraz << endl;
		if(w!=1) {
			teraz=max(teraz, przedzial(1, w-1)+a-c);
		}	
		//cout << teraz << endl;
		if(w!=500000) {
			teraz=max(teraz, przedzial(w+1, 500000)+a-c);
		}	
		//cout << teraz << endl;
		Q.push({a, w, teraz});
		//cout << i << ' ' << teraz << endl;
		WYN=max(WYN, teraz);
	}	
	cout << WYN;
}