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

#define rep(a,b,c) for(auto a = (b); a != (c); a++)
#define repD(a,b,c) for(auto a = (b); a != (c); a--)
#define repIn(a, b) for(auto& a : (b))
#define repIn2(a, b, c) for(auto& [a, b] : (c))

constexpr bool dbg = 0;
#define DEBUG if constexpr(dbg)
#define DC DEBUG std::cerr
#define eol std::endl

#define ll long long
#define pb push_back

using namespace std;

constexpr int maxn = 5e5 + 7;
ll bestEnding[maxn][2], bestOverall[2];
ll arr[maxn];

int main() {
    ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
    ll n, c;
    cin >> n >> c;
    ll which = 1, prv = -1;
    ll sz, tp;
    vector<int> changes;
    rep(i, 0, n) {
        cin >> sz >> tp;
        if(sz != prv) {
            which ^= 1;
            bestOverall[which] = max(bestOverall[which], bestOverall[which ^ 1]);
            repIn(i, changes) bestEnding[i][which] = max(bestEnding[i][which], bestEnding[i][which ^ 1]);
            changes.clear();
        }
        prv = sz;
        ll myBest = max(bestEnding[tp][which ^ 1], bestOverall[which ^ 1] - c) + sz;
        DC << myBest << eol;
        bestEnding[tp][which] = max(bestEnding[tp][which], myBest);
        bestOverall[which] = max(bestOverall[which], myBest);
        changes.pb(tp);
    }
    cout << max(bestOverall[which], bestOverall[which ^ 1]) << '\n';
}