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
#include <bits/stdc++.h>
#define fi first
#define sc second
#define pb push_back
#define rep(i,p,k) for(int i=(p);i<(k);++i)
#define forn(i,p,k) for(int i=(p);i<=(k);++i)
#define forr(i,k,p) for(int i=(k)-1;i>=(p);--i)
#define each(a,b) for(auto&a:b)
#define all(v)  begin(v), end(v)
#define RET(smth)   return void(cout<<(smth)<<'\n');
#define sz(v) (int)v.size()
using namespace std;
using pii = pair<int,int>;
using ll = long long;
using lll = __int128_t;
using Vi = vector<int>;
#ifdef DEBUG
#include "debug.h"
#else
#define debug(...) ;
#endif

const int MM = 500001;
ll dp[MM];


int main() {
#ifndef DEBUG
    cin.tie(0) -> sync_with_stdio(0);
#endif
    int n,c; cin >> n >> c;
    vector<pair<int,int>> t(n);
    for(auto &[a,w] : t) cin >> a >> w;
    reverse(all(t));
    int lst = t[0].fi;
    vector<pair<ll,int>> updates;
    pair<ll,int> bst{0,0};
    auto apply = [c](pair<ll, int> cr, int a, int w) -> pair<ll, int> {
        auto [aa, ww] = cr;
        return {aa+a-(ww > 0 && w != ww ? c : 0), w};
    };
    for(auto [a,w] : t) {
        if(a != lst) {
            updates.push_back(bst);
            for(auto [aa,ww] : updates) {
                bst = max(bst, {aa,ww});
                dp[ww] = max(dp[ww], aa);
            }
            updates.clear();
            lst = a;
        }
        updates.push_back(apply(bst, a, w));
        updates.push_back(apply({dp[w],w}, a, w));
    }
    updates.push_back(bst);
    cout << max_element(all(updates))->first << '\n';
    return 0;
}