Problem:
Score : 400 points

Problem Statement

There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it.

You can take and complete at most one of these jobs in a day.

However, you cannot retake a job that you have already done.

Find the maximum total reward that you can earn no later than M days from today.

You can already start working today.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i \leq 10^5

1 \leq B_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the maximum total reward that you can earn no later than M days from today.

Sample Input 1

3 4
4 3
4 1
2 2

Sample Output 1

5

You can earn the total reward of 5 by taking the jobs as follows:

Take and complete the first job today. You will earn the reward of 3 after four days from today.

Take and complete the third job tomorrow. You will earn the reward of 2 after two days from tomorrow, that is, after three days from today.

Sample Input 2

5 3
1 2
1 3
1 4
2 1
2 3

Sample Output 2

10

Sample Input 3

1 1
2 1

Sample Output 3

0

Solution in C++14 (GCC 5.4.1) (judge verdict: Accepted)

#include <bits/stdc++.h>
using namespace std;
using P = pair<int, int>;

template <typename T>
struct SegmentTree {
  using F = function<T(T, T)>;

  int n;
  T init;
  F f;
  vector<T> data;

  SegmentTree() {}
  SegmentTree(int n_, vector<T> v = vector<T>(),
              F f = [](T a, T b) { return max(a, b); }, T init = -1)
      : f(f), init(init) {
    n = 1;
    while (n < n_) n *= 2;
    data.assign(n * 2 - 1, init);
    if (n_ == v.size()) build(v);
  }
  void build(vector<T> v) {
    for (int i = 0; i < v.size(); ++i) data[i + n - 1] = v[i];
    for (int i = n - 2; i >= 0; --i) {
      data[i] = f(data[i * 2 + 1], data[i * 2 + 2]);
    }
  }
  void update(int k, T x) {
    k += n - 1;
    data[k] = x;
    while (k > 0) {
      k = (k - 1) / 2;
      data[k] = f(data[k * 2 + 1], data[k * 2 + 2]);
    }
  }
  T query(int a, int b, int k = 0, int l = 0, int r = -1) {
    if (r < 0) r = n;
    if (b <= l || r <= a) return init;
    if (a <= l && r <= b) return data[k];
    T vl = query(a, b, k * 2 + 1, l, (l + r) / 2);
    T vr = query(a, b, k * 2 + 2, (l + r) / 2, r);
    return f(vl, vr);
  }
};

int main() {
  int n, m;
  cin >> n >> m;
  vector<P> p;
  for (int i = 0; i < n; i++) {
    int a, b;
    cin >> a >> b;
    if (a > m) continue;
    p.push_back({b, a});
  }
  sort(rbegin(p), rend(p));
  vector<int> v(m);
  for (int i = 0; i < m; i++) v[i] = i;
  SegmentTree<int> seg(m, v);
  int ans = 0;
  for (int i = 0; i < p.size(); i++) {
    int a, b;
    tie(b, a) = p[i];
    int cur = seg.query(0, m - a + 1);
    if (cur < 0) continue;
    seg.update(cur, -1);
    ans += b;
  }
  cout << ans << endl;
}