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
//fast
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;

#define rep(n) for(int i = 0 ; i<n ; i++)
#define all(x) x.begin(),x.end()
#define pb push_back

const int base = 5e5+7;
pair<ll,int> maks[base][2];

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int n,c;
    cin >> n >> c;
    pair<ll,int> best[2];
    int a[n+1];
    int w[n+1];
    a[0] = 0;
    w[0] = 0;
    rep(n) cin >> a[i+1] >> w[i+1];
    ll xd = 0;
    for (int i = 1 ; i<=n ; i++){
        ll x = a[i];
        if (a[best[0].second]==a[i]){
            x+=best[1].first-c;
        }else{
            x+=best[0].first-c;
        }
        ll y = a[i];
        if (a[maks[w[i]][0].second]==a[i]){
            y+=maks[w[i]][1].first;
        }else{
            y+=maks[w[i]][0].first;
        }

        x = max(x,y);
        xd = max(xd,x);

        if (a[best[0].second]==a[i]){
            best[0].first=max(best[0].first,x);
        }else if (best[0].first<x){
            swap(best[0],best[1]);
            best[0] = {x,i};
        }
        if (a[maks[w[i]][0].second]==a[i]){
            maks[w[i]][0].first=max(maks[w[i]][0].first,x);
        }else if (maks[w[i]][0].first<x){
            swap(maks[w[i]][0],maks[w[i]][1]);
            maks[w[i]][0] = {x,i};
        }
    }
    cout << xd << '\n';
}