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 Ruby (2.7.1) (judge verdict: Accepted)

class Array
  def add_heap(x)
    self.push(x)
    i = self.length - 1
    while i != 0 and self[(i-1)/2] > self[i] do
      tmp = self[(i-1)/2]
      self[(i-1)/2] = self[i]
      self[i] = tmp
      i = (i-1)/2
    end
  end
  def delete_heap_index(i)
    self[i] = self[-1]
    self.pop
    while self[2*i+1] != nil do
      if self[2*i+2] != nil and self[2*i+2] < self[2*i+1] then
        j = 2 * i + 2
      else
        j = 2 * i + 1
      end
      if self[j] < self[i] then
        tmp = self[i]
        self[i] = self[j]
        self[j] = tmp
        i = j
      else
        break
      end
    end
  end
end

lines = []
while line = gets
    lines << line.chomp.split(' ').map(&:to_i)
end

N = lines[0][0]
M = lines[0][1]
C = 10 ** 10

job = []
for i in 1..N do
  job[i-1] = lines[i][0] * C + lines[i][1]
end
job.sort!
    
t = 1
ans = 0
cand = []
while t <= M do
  loop do
    if job != [] then
      date = job[0] / C
      pay = job[0] % C
    else
      break
    end
    if date <= t then
      cand.add_heap(-pay)
      job.shift
    else
      break
    end
  end
  if cand != [] then
    ans -= cand[0]
    cand.delete_heap_index(0)
  end
  t += 1
end
puts ans