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 Go (1.6) (judge verdict: Accepted)

package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
)

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

type item struct {
	index int
	A     int
	B     int
}

type priorityQueue []*item

func (pq priorityQueue) Len() int {
	return len(pq)
}

func (pq priorityQueue) Less(i, j int) bool {
	return pq[i].B > pq[j].B
}

func (pq priorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *priorityQueue) Push(x interface{}) {
	item := x.(*item)
	item.index = len(*pq)
	*pq = append(*pq, item)
}

func (pq *priorityQueue) Pop() interface{} {
	n := len(*pq)
	item := (*pq)[n-1]
	item.index = -1
	*pq = (*pq)[0 : n-1]
	return item
}

func main() {
	input := bufio.NewReader(os.Stdin)

	var N, M int
	fmt.Fscanf(input, "%d %d\n", &N, &M)
	A := make([]int, N)
	B := make([]int, N)
	for n := 0; n < N; n++ {
		fmt.Fscanf(input, "%d %d\n", &A[n], &B[n])
	}

	m := make([][]int, M+1)
	for i := range m {
		m[i] = make([]int, 0)
	}
	for n := 0; n < N; n++ {
		if A[n] <= M {
			m[A[n]] = append(m[A[n]], n)
		}
	}

	pq := make(priorityQueue, 0)
	heap.Init(&pq)
	var ans int
	for i := 1; i <= M; i++ {
		for _, n := range m[i] {
			item := &item{
				A: A[n],
				B: B[n],
			}
			heap.Push(&pq, item)
			heap.Fix(&pq, item.index)
		}
		if pq.Len() > 0 {
			x := heap.Pop(&pq)
			item := x.(*item)
			ans += item.B
		}
	}
	fmt.Println(ans)
}