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
77
// #pragma GCC optimize("O3")
// #pragma GCC optimize("Ofast")
// #pragma GCC optimize("unroll-loops")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,bmi,bmi2,lzcnt,abm,mmx,avx,avx2,tune=native")

#include <bits/stdc++.h>

using namespace std;

// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
// using namespace __gnu_pbds;

// template <typename T>
// using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;

#define rep(i, j) for (int i = 0; i < ((int)(j)); i++)
#define pb push_back
#define pf push_front
#define st first
#define nd second
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define get_unique(x) x.erase(unique(all(x)), x.end());

ll best[500005];
ll best_bigger = 0, best_same = 0;
ll size_bigger = 1e9, size_same = 1e9;

void TEST([[maybe_unused]] int testcase_i) {
    ll n, c;
    cin >> n >> c;
    vector<pair<ll, ll>> v;
    rep(i, n) {
        ll a, b;
        cin >> a >> b;
        v.emplace_back(a, b);
    }
    sort(all(v));
    get_unique(v);
    reverse(all(v));
    for(auto [h, w] : v) {
        if(h < size_same) {
            best_bigger = best_same;
            size_bigger = size_same;
        }
        best_same = max({best_bigger + h - c, best_same, best[w] + h});
        size_same = h;
        best[w] = max(best[w] + h, best_bigger + h - c);
    }
    cout << best_same;
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);

  // cout << setprecision(20) << fixed;

  // srand(time(NULL));

  // freopen("sorting.in", "r", stdin);
  // freopen("sorting.out", "w", stdout);

  int t = 1;
  // cin >> t;
  rep(i, t) {
    TEST(i);
  }

  return 0;
}