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-----
3 4
4 3
4 1
2 2

-----Sample Output-----
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.

Difficulty: interview

Starter code:

Solutions:
import sys, math
from functools import lru_cache
import numpy as np
import heapq
from collections import defaultdict
sys.setrecursionlimit(10**9)
MOD = 10**9+7

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return list(map(int, input().split()))

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]


def lcm(a, b):
    return a*b//math.gcd(a, b)


def main():
    N, M = mi()
    A, B = i2(N)
    ans = 0

    d = defaultdict(list)
    for i in range(N):
        d[A[i]].append(B[i])

    h = []
    heapq.heapify(h)

    for i in range(1, M+1):
        for v in d[i]:
            heapq.heappush(h, -v)
        if h:
            ans -= heapq.heappop(h)
        else:
            continue

    print(ans)



def __starting_point():
    main()

__starting_point()

import sys
import heapq

sys.setrecursionlimit(10 ** 8)
ini = lambda: int(sys.stdin.readline())
inl = lambda: [int(x) for x in sys.stdin.readline().split()]
ins = lambda: sys.stdin.readline().rstrip()

N, M = inl()


class MinHeap(object):
    def __init__(self):
        self.h = []

    def push(self, x):
        heapq.heappush(self.h, x)

    def pop(self):
        return heapq.heappop(self.h)

    def __getitem__(self, i):
        return self.h[i]

    def __len__(self):
        return len(self.h)

    def __bool__(self):
        return bool(self.h)


class MaxHeap(MinHeap):
    class Negator(object):
        def __init__(self, val):
            self.val = val

        def __lt__(self, other):
            return self.val > other.val

        def __eq__(self, other):
            return self.val == other.val

        def __str__(self):
            return str(self.val)

    def push(self, x):
        heapq.heappush(self.h, self.Negator(x))

    def pop(self):
        return heapq.heappop(self.h).val


def solve():
    jobs = []
    for i in range(N):
        a, b = inl()
        jobs.append((a, b))
    jobs.sort()

    hp = MaxHeap()
    ans = 0
    j = 0
    for d in range(1, M + 1):
        while j < N and jobs[j][0] == d:
            a, b = jobs[j]
            hp.push(b)
            j += 1
        if hp:
            ans += hp.pop()
    return ans


print((solve()))


import sys
from heapq import heappush, heappop

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n, m = list(map(int, input().split()))
    AB = [[] for _ in range(m)]
    for _ in range(n):
        a, b = list(map(int, input().split()))
        if a <= m:
            AB[m - a].append(b)

    que = []
    res = 0
    for i in reversed(list(range(m))):
        for b in AB[i]:
            heappush(que, -b)
        if que:
            res += heappop(que) * -1
    print(res)


def __starting_point():
    resolve()

__starting_point()

import heapq

n,m = map(int, input().split())
ab = [[] * (m+1) for i in range(m+1)]
for i in range(n):
  a,b = map(int, input().split())
  if m - a < 0:
    continue
  ab[a].append(b)

q=[]
ans = 0
heapq.heapify(q)
for i in range(1,m+1):
  for j in ab[i]:
    heapq.heappush(q, j*(-1))
  if q:
    b = heapq.heappop(q)
    ans += (-1) * b
print(ans)

import sys
import heapq
def input(): return sys.stdin.readline().rstrip()
 
def main():
    n,m=map(int, input().split())
    li=[]
    for _ in range(n):
        b,a=map(int, input().split())
        if m-b >= 0:
            li.append([a,m-b])
    li.sort(key=lambda x: x[1])
    h=[]
    for i in li:
        if len(h) >= i[1]+1:
            heapq.heappushpop(h, i[0])
        else:
            heapq.heappush(h, i[0])
    print(sum(h))
    

def __starting_point():
    main()
__starting_point()

from heapq import*
(N, M), *t = [map(int, s.split()) for s in open(0)]
v = [[] for _ in [None] * 10**5]
for a, b in t:
    v[a - 1] += b,
z = 0
q = []
for i in v[:M]:
    for j in i:
        heappush(q, -j)
    if q:
        z += -heappop(q)
print(z)

import heapq

N,M = list(map(int, input().split()))


rinsetuList = [[] for _ in range(100001)]

for _ in range(N):
    A, B = list(map(int, input().split()))
    rinsetuList[A].append(B)

#print(rinsetuList[:M+1])

work_list = []
hpq = heapq.heapify(work_list)

ans = 0
for rinsetu in rinsetuList[:M+1]:
    for money in rinsetu:
        heapq.heappush(work_list, money * (-1))
    if(len(work_list) != 0):
        ans += heapq.heappop(work_list) * (-1)

#    print(ans)
#    print(work_list)

print(ans)

import heapq
N, M = map(int, input().split())

jobs = [[] for _ in range(M)]
for _ in range(N):
    A, B = map(int, input().split())
    if A > M:
        continue
    jobs[A-1].append(-B)

total = 0
heap = []
for i in range(M):
    for job in jobs[i]:
        heapq.heappush(heap, job)

    if len(heap) == 0:
        continue
    else:
        total += -heapq.heappop(heap)

print(total)

import heapq

n, m = map(int, input().split())
ab = sorted([list(map(int, input().split())) for _ in range(n)], key=lambda x: (-x[0], x[1]))

q = []
ans = 0
for i in range(1, m+1):
    while ab and ab[-1][0] == i:
        a, b = ab.pop()
        heapq.heappush(q, -b)
    if q:
        ans -= heapq.heappop(q)
print(ans)

from heapq import *
N,M = map(int,input().split())
L = [[] for m in range(M)]
H = []
ans = 0

for n in range(N):
  a,b = map(int,input().split())
  if a<=M:
    L[M-a]+=[b]
    
for m in range(M-1,-1,-1):
  for l in L[m][::-1]:
    heappush(H,-l)
  if 0<len(H):
    ans-=heappop(H)

print(ans)

def insertHeap(array, val):
    array.append(val)
    n = len(array)-1
    while n != 0:
        parent = int((n - 1) / 2)
        if array[n] > array[parent]:
            tmp = array[n]
            array[n] = array[parent]
            array[parent] = tmp
            n = parent
        else:
            break
    return array

def desertHeap(array):
    if array == []:
      return None
    array[0], array[-1] = array[-1], array[0]
    res = array.pop(-1)
    n = len(array)
    if n == 0 or n == 1: 
      return res
    parent = 0
    while True:
        child = 2 * parent + 1
        if child >= n: break
        if (child + 1 < n) and array[child] < array[child + 1]:
            child += 1
        if array[parent] < array[child]:
            array[child], array[parent] = array[parent], array[child]
            parent = child;
        else:
            break
    return res

n, m = map(int, input().split())
 
li = [[] for j in range(10**5+1)]
 
for _ in range(n):
  a, b = map(int, input().split())
  li[a].append(b)
 
ans = 0
jobsHeap = []
for i in range(1, m+1):
  for val in li[i]:
    jobsHeap = insertHeap(jobsHeap, val)
  
  if jobsHeap != []:
    res = desertHeap(jobsHeap)
    ans += res
print(ans)

N,M = list(map(int,input().split()))
AB = [list(map(int,input().split())) for _ in range(N)]

AB.sort(key= lambda x:(-x[1],-x[0]))#報酬が高く、かつ、振り込みの日数が長いものからやるためのソート
memo = [0]*(10**5+1)#請け負うと決めた仕事の日のメモ。1がついている日は仕事がすでにある
work = [float('inf')]*(10**5+1)#振り込みまでに必要な日数のうち、前回請け負いを決めた日
noMore = float('inf') #これ以上の日数が振り込みにかかる仕事は受けれない
ans = 0
for a,b in AB:
    if a< noMore:#期日までに報酬が受け取れる仕事であること
        flag = 1
        for idx in range(min(M-a,work[a]),-1,-1):#この検索範囲の絞り込みがTLE解消の決め手。前回検索時に請け負った日またはM-a日以前の日
            if memo[idx] == 0:#仕事が請けられる
                ans += b#報酬を足す
                memo[idx]=1#仕事を受けたことの記録。この日はもう受けられない
                flag = 0#noMoreの更新分岐のため
                work[a] = idx#次回検索時のメモ
                break
        if flag ==1:#請けれる日が見つからなければ、今後この日数以上の日は受けれないので調べない
            noMore = a
    
print(ans)
    


from heapq import heapify, heappop, heappush
from collections import deque
N,M=list(map(int,input().split()))
A=[0]*N #ラグ
B=[0]*N #報酬
C=[0]*N
for i in range(N):
    A[i],B[i]= list(map(int,input().split()))
    C[i]=[A[i],B[i]]
C.sort()
D=deque(C)
reward=0
#print(D)

h=[]
heapify(h)

for i in range(M-1,-1,-1):   
    while D:
        e = D.popleft()
        if e[0]==M-i:
            heappush(h,-1*e[1])
        else:
            D.appendleft(e)
            break
    #print(h)
    if h:
        reward += (-1)*heappop(h)
        
print(reward)


import heapq
n, m = map(int, input().split())
d = [[] for _ in range(m)]
for _ in range(n):
    a, b = map(int, input().split())
    if a <= m:
        d[a-1].append(-b)

t = []
heapq.heapify(t)
ans = 0
for i in range(m):
    for dd in d[i]:
        heapq.heappush(t, dd)
    if t:
        ans += heapq.heappop(t)*(-1)
print(ans)

import heapq

n, m = map(int, input().split())
x = [[] for _ in range(m + 1)]
y = []
heapq.heapify(y)
for i in range(1, m + 1):
    heapq.heapify(x[i])
for _ in range(n):
    a, b = map(int, input().split())
    if a <= m:
        heapq.heappush(x[a], -b)
ans = 0
for i in range(1, m + 1):
    if x[i]:
        s = heapq.heappop(x[i])
        heapq.heappush(y, [s, i])
    if y:
        s, t = heapq.heappop(y)
        ans -= s
        if x[t]:
            s = heapq.heappop(x[t])
            heapq.heappush(y, [s, t])
print(ans)

import heapq

n, m = map(int, input().split())
ab = sorted([list(map(int, input().split())) for _ in range(n)], reverse=True)

c = []
ans = 0
for i in range(m):
    while len(ab) != 0 and ab[-1][0] <= i+1:
        _, b = ab.pop()
        heapq.heappush(c, -b)
    if c:
        ans += -heapq.heappop(c)
print(ans)

n, m = map(int, input().split())
ab = [[] for _ in range(m+1)]
for i in range(n):
  t = [int(inp) for inp in input().split()]
  if t[0] <= m:
    ab[t[0]].append(-t[1])
ans = 0
import heapq
h = ab[1]
heapq.heapify(h)
for i in range(1, m+1):
  if len(h) > 0:
    ans += heapq.heappop(h)
  if i != m:
    for t in ab[i+1]:
      heapq.heappush(h, t)
print(-ans)

from heapq import heappop, heappush 
N, M = list(map(int, input().split()))
score = 0
AB = [[] for i in range(M)]
for i in range(N):
  a, b = list(map(int, input().split()))
  if M - a >= 0:
    AB[M - a].append(b)
  
#print(AB)
queue = []
for i in range(1, M + 1):
  for j in AB[-i]:
    heappush(queue, -j)
  if queue != []:
    score += -1 * heappop(queue)
  
  #print(score, queue)  
print(score)  
  
  




from heapq import *
n,m=map(int,input().split())
ab=[]
ans=[[] for i in range(m)]
aa=0
for i in range(n):
    a,b=map(int,input().split())
    a-=1
    b*=-1
    ab.append((a,b))
ab.sort()
t=[]
heapify(t)
for a,b in ab:
    if a<m:
        ans[a].append(b)
for i in range(m):
    for j in ans[i]:
        heappush(t,j)
    if len(t)>0:
        tt=heappop(t)*(-1)
        aa+=tt
print(aa)

def main():
    import sys
    sys.setrecursionlimit(10**9)
    input = sys.stdin.readline
    from heapq import heappush, heappop

    N, M = list(map(int, input().split()))
    AB = [ [] for _ in range(100000) ]

    for _ in range(N):
        a, b = list(map(int, input().split()))
        AB[a-1].append(-b)

    ans = 0
    heap = []
    for a in range(M):
        for b in AB[a]:
            heappush(heap, b)
        if heap:
            ans -= heappop(heap)
    
    print(ans)

main()


import heapq

n, m = map(int, input().split())
A = [[] for _ in range(m)]
ans = 0

for i in range(n):
    a, b = map(int, input().split())
    if m-a < 0:
        continue
    else:
        A[m-a].append(b)

available = []

for i in range(m-1, -1, -1):
    for item in A[i]:
        heapq.heappush(available, -item)
    if available:
        ans += -heapq.heappop(available)

print(ans)

import heapq
n,m = map(int,input().split())
al = [[] for i in range(10**5)]
ans = 0
h = []
for i in range(n):
    a,b = map(int,input().split())
    al[a-1] += [-b]
for i in range(m):
    for j in al[i]:
        heapq.heappush(h,j)
    if h:
        ans -= heapq.heappop(h)
print(ans)

import heapq
n,m= map(int,input().split())
feeindays = [[] for _ in range(m)]
for i in range(n):
    a,b= map(int,input().split())
    if a<=m:feeindays[a-1]+=[b]
q=[]
heapq.heapify(q)
pay=0
for l in feeindays:
    for c in l:heapq.heappush(q,-c)
    if len(q)!=0:pay+=-1 * heapq.heappop(q)
print(pay)

n,m = map(int,input().split())
ab = [0]*n
V = [[] for i in range(m+1)]
for i in range(n):
    a,b = map(int,input().split())
    if a <= m:
        V[a].append(-b)

import heapq
q = []
ans = 0
heapq.heapify(q)
for i in range(1,m+1):
    for v in V[i]:
        heapq.heappush(q,v)

    if len(q) == 0:
        pass
    else:
        ans -= heapq.heappop(q)
print(ans)

import sys
readline = sys.stdin.readline
 
N,M = map(int,readline().split())
from collections import defaultdict
tasks = defaultdict(list)
for i in range(N):
  a,b = map(int,readline().split())
  tasks[a].append(b)
  
import heapq as hq
q = []
ans = 0
for i in range(1, M + 1):
  newtask = tasks[i]
  for t in newtask:
    hq.heappush(q,-t)
  if q:
    ans += -hq.heappop(q)
 
print(ans)

#!/usr/bin/env python3
from collections import deque, Counter
from heapq import heappop, heappush
from bisect import bisect_right

def main():
    N, M = list(map(int, input().split()))
    AB = [[] for _ in range(10**5)]
    for i in range(N):
        a, b = list(map(int, input().split()))
        AB[a-1].append(b)
    
    q = []
    ans = 0
    i = 0
    while i < M:
        for ab in AB[i]:
            heappush(q,-ab)
        if q:
            ans -= heappop(q)
        i += 1
    print(ans)


def __starting_point():
    main()

__starting_point()

import heapq
n, m = list(map(int, input().split())) 

d = [[] for _ in range(m+1)]
for _ in range(n):
    a, b = list(map(int, input().split()))
    if a < m+1:
        d[a].append(b)

hq = []
heapq.heapify(hq)
ans = 0
for i in range(1, m+1): 
    if len(d[i]) > 0:
        for j in d[i]:
            heapq.heappush(hq, j*(-1))
    if len(hq) > 0:
        ans += heapq.heappop(hq)*(-1)
print(ans)


from heapq import heappush,heappop

n,m=[int(x) for x in input().rstrip().split()]
ab=[[] for i in range(10**5)]

for i in range(n):
  a,b=[int(x) for x in input().rstrip().split()]
  if a<=m:
    ab[m-a].append(-b)

ans=0
l=[]
for i in range(m-1,-1,-1):
  for b in ab[i]:
    heappush(l,b)

  if l:
    ans-=heappop(l)

print(ans)


import heapq

n, m = map(int,input().split())
ab = [[0] * 2 for i in range(n)]
for i in range(n):
    a, b = map(int,input().split())
    ab[i][0], ab[i][1] = a, -1*b
heapq.heapify(ab)

b = [0]
heapq.heapify(b)
ans = 0
for i in range(1, m+1):
    while ab:
        tmp = heapq.heappop(ab)
        if tmp[0] <= i:
            heapq.heappush(b, tmp[1])    
        else:
            heapq.heappush(ab, tmp)
            break
    if b:
        ans -= heapq.heappop(b)
print(ans)

import heapq

N, M = list(map(int, input().split()))

AB = []
can = [[] for i in range(M+1)]
for i in range(N):
    a, b = list(map(int, input().split()))
    AB.append([a, b])
    if M - a >= 0:
        can[M-a].append(-b)

que = []
ans = 0
for i in range(M, -1, -1):
    now_list = can[i]
    for j in range(len(now_list)):
        heapq.heappush(que, now_list[j])
    if que:
        ans += heapq.heappop(que)

print((-ans))


import sys
from heapq import heappush, heappop

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n, m = list(map(int, input().split()))
    B = [[] for _ in range(m)]
    for _ in range(n):
        a, b = list(map(int, input().split()))
        if m - a >= 0:
            B[m - a].append(b)

    que = []
    res = 0
    for i in reversed(list(range(m))):
        for b in B[i]:
            heappush(que, -b)
        if que:
            res += heappop(que) * (-1)
    print(res)


def __starting_point():
    resolve()

__starting_point()

import sys
from heapq import heappop, heappush

input = sys.stdin.readline


def main():
    MAX_A = 10 ** 5
    N, M = list(map(int, input().split()))
    AB = [[] for _ in range(MAX_A + 1)]
    for i in range(N):
        A, B = list(map(int, input().split()))
        AB[A].append(-B)

    p_queue = []
    ans = 0
    for m in range(1, M + 1):
        for b in AB[m]:
            heappush(p_queue, b)
        if p_queue:
            x = heappop(p_queue)
            x *= -1
            ans += x

    print(ans)


def __starting_point():
    main()

__starting_point()

def resolve():    
    import heapq
    n,m=map(int,input().split())
    ab=[list(map(int,input().split())) for _ in range(n)]
    b=[[] for _ in range(10**5+1)]
    for i,j in ab:
        b[i].append(-j)
    q=[]
    ans=0
    for i in range(1,m+1):
        for j in b[i]:
            heapq.heappush(q,j)
        if q:
            ans+=heapq.heappop(q)
    print(-ans)
        
def __starting_point():
    resolve()
__starting_point()

import heapq
from collections import defaultdict

n, m = list(map(int, input().split()))

cnt = defaultdict(list)
for _ in range(n):
    a, b = list(map(int, input().split()))
    cnt[a].append(b)

t = []
heapq.heapify(t)
ans = 0
for i in range(1, m+1):
    for j in cnt[i]:
        heapq.heappush(t, -j)
    if t: ans -= heapq.heappop(t)

print(ans)


import heapq

from typing import List


def main():
    n, k = list(map(int, input().split()))
    v = []
    for _ in range(n):
        a, b = list(map(int, input().split()))
        v.append((a, b))

    print((sv(v, k)))


def sv(v: List[List[int]], k: int) -> int:
    vv = {}
    for a, b in v:
        if str(a) in vv:
            vv[str(a)].append(b)
        else:
            vv[str(a)] = []
            vv[str(a)].append(b)

    hp = []
    result = 0
    bk = 1
    while k >= bk:
        if str(bk) in vv:
            for b in vv[str(bk)]:
                heapq.heappush(hp, -b)
        if len(hp) > 0:
            result += -heapq.heappop(hp)
        bk += 1

    return result


def __starting_point():
    main()

__starting_point()

_,m=map(int,input().split())
work=sorted([tuple(map(int,input().split()))for k in range(_)],key=lambda x:(-x[0],x[1]))
from heapq import heapify, heappop, heappush
now=[]
#print(work)
ans=0
for i in range(1,m+1):
    while work and work[-1][0]<=i:
        a,b=work.pop()
        heappush(now,-b)
        #print(a,b)
    
    if now:
        ans-=heappop(now)
    #print(i,ans)
print(ans)

from heapq import*
(N, M), *t = [map(int, s.split()) for s in open(0)]
q = [0] * 10**5
v = [[] for _ in q]
for a, b in t:
    v[a - 1] += b,
z = 0
for i in v[:M]:
    for j in i:
        heappush(q, -j)
    z += -heappop(q)
print(z)

#<D>
from heapq import heappush, heappop
import sys
input = sys.stdin.readline
N, M = list(map(int, input().split()))
X = sorted([list(map(int, input().split())) for n in range(N)], key = lambda x: x[0])
#print(X)
hq = []
ans, j = 0, 0

for i in range(1, M + 1): #M - i日後にするバイトを決める
    while (j < N) and (X[j][0] <= i):
        heappush(hq, -X[j][1]) # 候補の追加
        j += 1
    if len(hq):
        ans += - heappop(hq) #候補があるなら候補から最大値を取り出す
print(ans)


import heapq
#解説の方法
N,M = list(map(int,input().split()))
AB = [[] for _ in range(10**5+1)]#報酬振り込み日数ごとに報酬を格納
for _ in range(N):
    a,b = list(map(int,input().split()))
    AB[a].append(-b)
q = []
heapq.heapify(q)
ans =0
for i in range(1,M+1):
    for b in AB[i]:
        heapq.heappush(q,b)
    if len(q)>0:
        ans += -heapq.heappop(q)
print(ans)



import heapq

n, m = map(int, input().split())
ab = []
for i in range(n):
    ab.append(list(map(int, input().split())))
ab.sort()
ans = 0
num = 0
queue = []
heapq.heapify(queue)
for i in range(1, m + 1):
    if num < n:
        while ab[num][0] <= i:
            heapq.heappush(queue, [-ab[num][1], ab[num][0]])
            num += 1
            if num == n:
                break
    if len(queue):
        temp = heapq.heappop(queue)
        ans += -temp[0]
print(ans)

import heapq
N, M = list(map(int, input().split()))
AB = [list(map(int, input().split())) for _ in range(N)]

AB = sorted(AB, key=lambda x: x[0])

x = 0
res = 0

hq = []
heapq.heapify(hq)

for i in range(M):
    for j in range(x, N):
        if AB[j][0] > i+1:
            x = j
            break
        heapq.heappush(hq, AB[j][1]*-1)
    else:
        x = N
    
    if hq:
        res += heapq.heappop(hq)*-1

print(res)


import heapq
n , m = list(map(int, input().split()))
ab=[[] for i in range(10**5)]

for i in range(n):
    a , b = list(map(int, input().split()))
    ab[a-1].append(b*(-1))

que=[]
ans = 0
for i in range(m):
    for b in ab[i]:
        heapq.heappush(que,b)
    if que:
        ans+=heapq.heappop(que)
print((ans*(-1)))


#import math
#import itertools
#import numpy as np
import heapq
#from collections import deque
# sys.setrecursionlimit(10 ** 6)
#mod = 10 ** 9 + 7
#INF = 10 ** 9
#PI = 3.14159265358979323846

INT = lambda: int(input())
INTM = lambda: map(int,input().split())
STRM = lambda: map(str,input().split())
STR = lambda: str(input())
LIST = lambda: list(map(int,input().split()))
LISTS = lambda: list(map(str,input().split()))

def do():
    n,m=INTM()
    ptj=[[] for i in range(10**5)]
    ans=0
    for i in range(n):
        a,b=INTM()
        a-=1
        b*=(-1)
        ptj[a].append(b)
    h=[]
    for i in range(m):
        for p in ptj[i]:
            heapq.heappush(h,p)
        if len(h)!=0:
            ans+=heapq.heappop(h)
        #print(ans)
    print(0-ans)
    

def __starting_point():
    do()
__starting_point()

import heapq

def main():
    n, m = map(int, input().split())
    data = {}
    priorityQ = []
    for _ in range(n):
        a, b = map(int, input().split())
        if a <= m:
            if a in data:
                data[a].append(b)
            else:
                data[a] = [b]
    ans = 0
    for i in range(1, m+1):
        if i in data.keys():
            for k in data[i]:
                heapq.heappush(priorityQ, -k)
        if priorityQ:
            ans -= heapq.heappop(priorityQ)
    print(ans)
    return

def __starting_point():
    main()
__starting_point()

import heapq
N,M=map(int,input().split())
AB=[[]for i in range(10**5+1)]
for i in range(N):
    a,b=map(int,input().split())
    AB[a].append(-b)
q=[]
heapq.heapify(q)
ans=0
for i in range(1,M+1):
    for b in AB[i]:
        heapq.heappush(q,b)
    if len(q)>0:
        ans+=-heapq.heappop(q)
print(ans)

import sys
readline = sys.stdin.readline

N,M = map(int,readline().split())
from collections import defaultdict
tasks = defaultdict(list)
for i in range(N):
  a,b = map(int,readline().split())
  tasks[a].append(b)
  
import heapq as hq
q = []
ans = 0
for i in range(1, M + 1):
  newtask = tasks[i]
  for t in newtask:
    hq.heappush(q,-t)
  if q:
    ans += -hq.heappop(q)

print(ans)

from heapq import heappush,heappop

n,m=[int(x) for x in input().rstrip().split()]
ab=[[] for i in range(10**5)]

for i in range(n):
  a,b=[int(x) for x in input().rstrip().split()]
  ab[a-1].append(-b)

ans=0
time=0
l=[]
for i in range(m):
  for b in ab[i]:
    heappush(l,b)
  if l:
    ans-=heappop(l)

print(ans)

import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    N, M = LI()
    AB = [LI() for _ in range(N)]

    W = [[] for _ in range(M + 1)]
    for a, b in AB:
        if 0 <= M - a:
            W[M-a].append(b)
    # print(W)

    # 選択肢の少ない後ろの日付から決めていく
    ans = 0
    hq = []
    for i in reversed(W):
        for j in i:
            heapq.heappush(hq, -j)
        if hq:
            ans -= heapq.heappop(hq)

    print(ans)

def __starting_point():
    resolve()

__starting_point()

from heapq import heapify,heappop,heappush
n,m=map(int,input().split())
l=[[]for i in range(10**5)]
ans=0
for i in range(n):a,b=map(int,input().split());l[a-1].append(-b)
for i in range(10**5):heapify(l[i])
p = []
heapify(p)
for i in range(m):
 if len(l[i])!=0:heappush(p,[heappop(l[i]),i])
 if len(p)!=0:
  x=heappop(p)
  ans+=-x[0]
  if len(l[x[1]])!=0:heappush(p,[heappop(l[x[1]]),x[1]])            
print(ans)

import heapq

n, m = map(int, input().split())
que = []
for _ in range(n):
    a, b = map(int, input().split())
    que.append((-b, a))
que.sort(key=lambda x: x[1], reverse=True)

def solve(que, m):
    ans = 0
    h = []
    heapq.heapify(h)
    for i in range(1, m + 1):
        while len(que) != 0 and que[-1][1] <= i:
            tmp = que.pop()
            heapq.heappush(h, tmp)
        if len(h) == 0: continue
        tmp = heapq.heappop(h)
        ans -= tmp[0]
    return ans

print(solve(que, m))

n,m=map(int,input().split())
ab=[list(map(int,input().split()))for _ in range(n)]+[[100000000,0]]
for i in range(m):ab.append([i+1,0])
ab.sort()
from heapq import heappop,heappush
h=[]
j=0
ans=0
for i in range(1,m+1):
  while ab[j][0]<=i:
    heappush(h,-ab[j][1])
    j+=1
  ans-=heappop(h)
print(ans)

import heapq

N, M = list(map(int, input().split()))
AB = [[] for i in range(10**5+1)]

for i in range(N):
    A, B = list(map(int, input().split()))
    AB[A].append(-B)

hq = []
heapq.heapify(hq)

ans = 0
for i in range(1, M+1):
    for b in AB[i]:
        heapq.heappush(hq, b)

    if len(hq) > 0:
        ans += -heapq.heappop(hq)

print(ans)


from operator import itemgetter
from collections import defaultdict
import heapq

n,m = list(map(int,input().split()))



d = defaultdict(list)
for i in range(n):
  a,b = list(map(int,input().split()))
  d[a].append(-b)
# l = sorted(l, key=itemgetter(1))
# l = l[::-1]
# print(d)
Q = []
heapq.heapify(Q)

ans = 0
for i in range(1,m+1):
    for j in d[i]:
      heapq.heappush(Q,j)
    
    if Q:ans += -heapq.heappop(Q)
    # print(ans,i)
print(ans)


import heapq
n,m=map(int,input().split())
t=[[] for _ in range(m+1)]
for i in range(n):
    a,b=map(int,input().split())
    if a>m:
        continue
    t[a].append(b)
ans=0
h=[]
for l in t:
    for i in l:
        heapq.heappush(h,-i)
    if h:
        ans-=heapq.heappop(h)
print(ans)

from heapq import heappop,heappush
from collections import defaultdict

N, M = map(int, input().split())
D = defaultdict(list)

for _ in range(N):
  A, B = map(int, input().split())
  D[A].append(B)

H = []
ans = [0]*(M+1)

for i in range(1, M+1):
  for j in D[i]:
    heappush(H, -j)
  if H:
    a = heappop(H)
    ans[i] = -a

print(sum(ans))

import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return list(map(int, input().split()))
def LIST(): return list(map(int, input().split()))
def ZIP(n): return list(zip(*(MAP() for _ in range(n))))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
#from decimal import *

N, M = MAP()
AB = [LIST() for _ in range(N)]
AB.sort(key = lambda x: x[0])

ans = 0
i = 0
B = []
for j in range(1, M+1):
	while i < N and AB[i][0] <= j:
		heappush(B, -AB[i][1])
		i += 1
	if B:
		ans += -heappop(B)

print(ans)


import heapq

N, M = map(int, input().split())
jobs = [[] for i in range(M)]

for i in range(N):
    A, B = map(int, input().split())
    if A - 1 < M:
        jobs[A-1].append(B)

q = []
heapq.heapify(q)
ans = 0
for i in range(M):
    for j in jobs[i]:
        heapq.heappush(q, -j)
    if len(q) != 0:
        ans += -heapq.heappop(q)

print(ans)

N,K=list(map(int,input().split()))
l=[]
for i in range(N):
   l.append(list(map(int,input().split())))
l.sort()
import heapq
X=[]
S=0
ans=0
heapq.heapify(X)
for i in range(1,K+1):
   for j in range(S,N):
      if l[j][0]<=i:
         S+=1
         heapq.heappush(X,l[j][1]*-1)
      else:
         break
   try:
      tmp=heapq.heappop(X)
      ans+=tmp*-1
   except IndexError:
      continue
print(ans)

import heapq
n, m = map(int, input().split())
limit = [[] for i in range(m)]
for i in range(n):
    a, b = map(int, input().split())
    if a > m:
        # 間に合わないので使えない        
        continue
    # m-a日目までに取り掛かれば間に合うバイトを格納
    limit[m-a].append(b)

available = []
ans = 0
for i in range(m-1, -1, -1):
    # 最終日から辿ることで、新たに選択不可となるバイトが生じない
    for item in limit[i]:
        heapq.heappush(available, -item)
    if available:
        ans += -heapq.heappop(available)
print(ans)

import sys
from itertools import accumulate

input = sys.stdin.readline


class SegmentTree:
    """Segment Tree class.

    Args:
        N (int): Number of elements
        X (list[int]): List for initialization
        func (callable): Function for interval.
        init_v (int): Initial value that does not affect `func`.
            For example, specify INF when `func = min`.

    References:
        <https://en.wikipedia.org/wiki/Segment_tree>
    """
    def __init__(self, N, X, func, init_v):
        N_ = 1
        while N_ < N: N_ *= 2
        self.N = N_
        self.func = func
        self.init_v = init_v
        self.__build(X)

    def __build(self, X):
        # Initialize all nodes
        self.node = [[self.init_v, -1] for _ in range(2 * self.N)]  # 1-based index

        # Elementary intervals are stored
        for i, x in enumerate(X, self.N):
            self.node[i] = [x, i - self.N + 1]

        # The internal nodes correspond to intervals that are the union of elementary intervals
        for i in range(self.N - 1, 0, -1):
            self.node[i] = self.func(self.node[i << 1], self.node[i << 1 | 1])

    def update(self, i, x):
        """Update the i-th node value to x.

        Args:
            i (int): index (1-based index)
            x (int): udpate value
        """
        i += self.N - 1
        self.node[i][0] = x
        while i > 1:
            i >>= 1
            self.node[i] = self.func(self.node[i << 1], self.node[i << 1 | 1])

    def query(self, l, r):
        """Query for right half-open interval [l, r).

        Args:
            l (int): index (1-based index)
            r (int): index (1-based index)
        """
        dst_l = [self.init_v, -1]
        dst_r = [self.init_v, -1]
        l += self.N - 1
        r += self.N - 1
        while l < r:
            if l & 1:
                dst_l = self.func(dst_l, self.node[l])
                l += 1
            if r & 1:
                r -= 1
                dst_r = self.func(self.node[r], dst_r)
            l >>= 1
            r >>= 1
        return self.func(dst_l, dst_r)


def func(a, b):
    return a if a[0] > b[0] else b


def main():
    N, M = list(map(int, input().split()))
    AB = [None] * N
    for i in range(N):
        AB[i] = tuple(map(int, input().split()))

    AB.sort(key=lambda x: x[0])
    B = [0] * N
    C = [0] * (1 + 10 ** 5)
    for i, (a, b) in enumerate(AB):
        B[i] = b
        C[a] += 1
    C = list(accumulate(C))

    st = SegmentTree(N, B, func, -1)
    ans = 0
    l = 1
    for r in C[1:M + 1]:
        if r == 0:
            continue
        x, i = st.query(l, r + 1)
        if x == -1:
            continue
        ans += x
        st.update(i, -1)

    print(ans)


def __starting_point():
    main()

__starting_point()

import heapq
n , m = map(int,input().split())
kouho = [[] for i in range(m)]
for i in range(n):
    a , b = map(int,input().split())
    if a <= m:
        kouho[a-1].append(-b)
ans = 0
p = []
heapq.heapify(p)

for i in range(m):

    for j in kouho[i]:
        heapq.heappush(p,j)
    if p:
        ans -= heapq.heappop(p)
print(ans)

from heapq import*
(N, M), *t = [map(int, s.split()) for s in open(0)]
q, z = [], 0
v = [[] for _ in [None] * 10**5]
for a, b in t:
    v[a - 1] += b,
for i in v[:M]:
    for j in i:
        heappush(q, -j)
    if q:
        z += -heappop(q)
print(z)

from heapq import heappop, heapify, heappush
from collections import defaultdict
N, M = list(map(int,input().split()))
d = defaultdict(list)
for i in range(N):
    a, b = list(map(int, input().split()))
    d[a].append(b)
h = []
ans = 0
for i in range(1, M+1):
    if len(d[i]) != 0:
        for x in d[i]:
            heappush(h, -x)
    if len(h) != 0:
        ans -= heappop(h)
print(ans)


import heapq
 
n,m=map(int,input().split())
mm=10**5+5
c=[[0] for i in range(mm)]
 
for i in range(n):
  a,b=map(int,input().split())
  c[a].append(b)
 
#print(c)
 
ans=0
h=[]
for i in reversed(range(m)):
  d=m-i
  for j in c[d]:
    heapq.heappush(h,-j)
  #heapq.heapify(h)
  ans+=-heapq.heappop(h)
 
print(ans)

from heapq import heappop,heappush,heapify
from collections import deque

N,M=map(int,input().split())
A,B,C = [0]*N,[0]*N,[0]*N
for i in range(N):
    A[i],B[i] = map(int,input().split())
    C[i]=[A[i],B[i]]
C.sort()
C=deque(C)

a=[]
heapify(a)
ans=0

for i in range(M,-1,-1):
    while C:
        if C[0][0]<=M-i:
            heappush(a,(-1)*C[0][1])
            C.popleft()
        else:
            break
    if len(a)>0:
        p = heappop(a)
        ans += (-1)*p
        
print(ans)

import sys
from heapq import heappush,heappop

lines = []
for line in sys.stdin:
    lines.append(line.rstrip('\r\n'))
#print(lines)
n,m = lines[0].split()
n = int(n)
m = int(m)

a=[]
for i in range(n):
    x,y = lines[i+1].split()
    x = int(x)
    y = int(y)*(-1)
    a.append((x,y))
a.sort()
a.append((0,0))

h = []

cur = 0
summ = 0
for i in range(1,m+1):
    while(cur<n and a[cur][0]<=i):
        heappush(h,a[cur][1])
        cur+=1
    if(len(h)>0):
        summ+=heappop(h)*(-1)
print(summ)
    


# m-1日目は、a<=1で最大報酬のアルバイトをやる
# m-2日目は、a<=2で最大報酬のアルバイトをやる（ただし、m-1日目に選択したアルバイトを除く）
# 以下この要領で後ろから決めていく
from collections import defaultdict
from heapq import heapify, heappush, heappop

n,m = list(map(int, input().split()))
d = defaultdict(list)
for _ in range(n):
    a,b = list(map(int, input().split()))
    d[a].append(b)

L = []
heapify(L)

ans = 0
for remain in range(1,m+1):
    for reward in d[remain]:
        heappush(L, -reward)
    if len(L):
        ans -= heappop(L)

print(ans)

import sys
from heapq import heappop, heappush
N, M = list(map(int, sys.stdin.readline().split()))
A = [[] for _ in [0]*M]
for line in sys.stdin:
    a, b = list(map(int, line.split()))
    if a > M:
        continue
    A[M-a].append(b)

ans = 0
q = []
for i, B in enumerate(A):
    for b in B:
        heappush(q, b)
        ans += b
    while len(q) > i+1:
        b = heappop(q)
        ans -= b
print(ans)


n,m=list(map(int,input().split()))
ab=[list(map(int, input().split())) for _ in range(n)]
ab=list(sorted(ab, key=lambda x: x[0]))

import heapq
hq=[]
ans=0
j=0
for i in range(1, m+1):  # m-i日後を考える
    while (j<n) and (ab[j][0]<=i):
        heapq.heappush(hq, -ab[j][1])
        j+=1
    if len(hq):
        ans+=-heapq.heappop(hq)

print(ans)


import heapq
N, M = list(map(int, input().split()))

AB = []
for _ in range(N):
    A, B = list(map(int, input().split()))
    AB.append((A, B))
AB = sorted(AB, key=lambda x: x[0])

hq = []
heapq.heapify(hq)  # リストhqのheap化

ans = 0
i = 0
for d in range(1, M+1):
    while i <= N-1 and AB[i][0] <= d:
        heapq.heappush(hq, -AB[i][1])  # heap化されたリストhqに要素xを追加
        i += 1
    if hq:
        ans -= heapq.heappop(hq)  # heap化されたリストhqから最小値を削除＆その最小値を出力
print(ans)


import heapq
n, m = list(map(int, input().split()))
byte = [[] for _ in range(100001)]

for _ in range(n):
    a, b = list(map(int, input().split()))
    byte[a].append(b)
search = []
day = 1
ans = 0
while day-1 != m:
    for b in byte[day]:
        heapq.heappush(search, -b)
    if not search:
        day += 1
        continue
    tmp = -heapq.heappop(search)
    ans += tmp
    day += 1

print(ans)





import heapq
n, m = list(map(int, input().split()))
byte = [[] for _ in range(m+2)]

for _ in range(n):
    a, b = list(map(int, input().split()))
    if a > m+1:
        continue
    byte[a].append(b)
search = []
day = 1
ans = 0
while day-1 != m:
    for b in byte[day]:
        heapq.heappush(search, -b)
    if not search:
        day += 1
        continue
    tmp = -heapq.heappop(search)
    ans += tmp
    day += 1

print(ans)





from heapq import heappop, heappush
import sys

def read_str(): return sys.stdin.readline().strip()
def read_int(): return int(sys.stdin.readline().strip())
def read_ints(): return list(map(int, sys.stdin.readline().strip().split()))
def read_str_split(): return list(sys.stdin.readline().strip())
def read_int_list(): return list(map(int, sys.stdin.readline().strip().split()))

def Main():
    n, m = read_ints()
    query = [[] for _ in range(m)]
    for _ in range(n):
        a, b = read_ints()
        if m - a < 0: continue
        query[m - a].append(b)

    total = 0
    que = []
    for i, b in enumerate(query):
        for x in b:
            heappush(que, x)
            total += x
        while len(que) > i + 1:
            x = heappop(que)
            total -= x
    print(total)

def __starting_point():
    Main()

__starting_point()

import sys
from collections import defaultdict
from heapq import heappop, heappush
N, M = list(map(int, sys.stdin.readline().split()))
A = defaultdict(list)
for line in sys.stdin:
    a, b = list(map(int, line.split()))
    if a <= M:
    	A[M-a].append(b)

ans = 0
q = []
for i, B in sorted(A.items()):
    for b in B:
        heappush(q, b)
        ans += b
    while len(q) > i+1:
        b = heappop(q)
        ans -= b
print(ans)


import sys
import queue

input_methods=['clipboard','file','key']
using_method=0
input_method=input_methods[using_method]

IN=lambda : map(int, input().split())
mod=1000000007

#+++++

class node:
	def __init__(self,a_val, a_parent=None):
		self.val=a_val
		self.parent=a_parent
		self.right=None
		self.left=None

def main2():
	n, m = IN()
	vl=[]
	for n in range(n):
		a,b = IN()
		vl.append((a,b))
		
	vl.sort(key=lambda x:-x[1])
	ret = 0
	nwdl=[-1]*(m+1) #list(range(m+1))
	for a, b in vl:
		j=m-a
		while j >= 0:
			if nwdl[j]==-1:
				nwdl[j]=0
				ret+=b
				break
			j-=1
		#pa((a,b,m-a,nwdl))
	print(ret)
	
	
def main():
	n, m = IN()
	st_day=[[] for _ in range(m+1)]
	for n in range(n):
		duration, pay = IN()
		if duration > m:
			continue
		st_day[m-duration].append(pay)
	
	pq=queue.PriorityQueue()
	ret = 0
	for di in range(m+1):
		day=m-di
		for pay in st_day[day]:
			pq.put(-pay)
		if not pq.empty():
			v = pq.get()
			ret -= v
	print(ret)
			
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

def __starting_point():
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)
__starting_point()

import heapq

def main():
    n, m = map(int, input().split())
    data = {}
    priorityQ = []
    for _ in range(n):
        a, b = map(int, input().split())
        if m + 1 - a >= 0:
            if m+1-a in data:
                data[m+1-a].append(b)
            else:
                data[m+1-a] = [b]
    ans = 0
    for i in range(m, 0, -1):
        if i in data.keys():
            for k in data[i]:
                heapq.heappush(priorityQ, -k)
        if priorityQ:
            ans -= heapq.heappop(priorityQ)
    print(ans)
    return

def __starting_point():
    main()
__starting_point()

from heapq import heappush, heappop

def readinput():
    n,m=list(map(int,input().split()))
    a=[]
    b=[]
    for i in range(n):
        ai,bi=list(map(int,input().split()))
        a.append(ai)
        b.append(bi)
    return n,m,a,b

def main(n,m,a,b):
    jobList=[]
    for i in range(10**5+1):
        jobList.append([])
    for i in range(n):
        jobList[a[i]].append(b[i])

    goodjobs=[]
    earn=0
    for d in range(1,m+1):
        for job in jobList[d]:
            heappush(goodjobs,-job)
        #print(goodjobs)
        if len(goodjobs)>0:
            earn+=heappop(goodjobs)
    return -earn

def __starting_point():
    n,m,a,b=readinput()
    ans=main(n,m,a,b)
    print(ans)

__starting_point()

from heapq import heappush, heappop

N, M = map(int, input().split())
AtoB = [[] for _ in range(M+1)]
for i in range(N):
    A, B = map(int, input().split())
    if A > M:
        continue
    AtoB[A].append(B)

# A が小さい順に増えていく
result = 0
que = [] # ヒープ
for Bs in AtoB:
    for B in Bs:
        heappush(que, -B) # Python3 のヒープはデフォルトで小さい順
    if que:
        result -= heappop(que)
print(result)

n,m=list(map(int, input().split()))
job_list=[]
for i in range(n):
    tmp=[int(x) for x in input().split()]
    job_list.append(tmp)
job_list.sort()

import heapq
k=0
ans=0
salary_list=[]
for i in range(1,m+1):
    while k<n and job_list[k][0]==i:
        heapq.heappush(salary_list,job_list[k][1]*(-1))
        k+=1
    if len(salary_list)>0:
        ans+=heapq.heappop(salary_list)
print(((-1)*ans))


from heapq import heapify, heappop, heappush
N,M = map(int,input().split())
A = [[] for _ in range(M+1)]
#HQ = []
for i in range(N):
  a,b = map(int,input().split())
  if a <= M:
    A[a].append(b)
#print(A)
ans = 0
L = []
for day in range(1,M+1):
  for t in A[day]:
    heappush(L,-t)
  #print(L)
  if not L:
    continue
  temp = heappop(L)
  ans += -temp
print(ans)  

import heapq

n,m=map(int,input().split())
mm=10**5+5
c=[[0] for i in range(mm)]

for i in range(n):
  a,b=map(int,input().split())
  c[a].append(b)

#print(c)

ans=0
h=[]
for i in reversed(range(m)):
  d=m-i
  for j in c[d]:
    heapq.heappush(h,-j)
  #heapq.heapify(h)
  ans+=-heapq.heappop(h)

print(ans)

import heapq as hq
import numpy as np

N, M = map(int, input().split())
job = [list(map(int, input().split())) for _ in range(N)]
ans = 0
job.sort()
job.append([np.inf, np.inf])
jobhq = []
index = 0
for day in range(1, M + 1):
    while day >= job[index][0]:
        hq.heappush(jobhq, - job[index][1])
        index += 1
    if jobhq:
        ans += - hq.heappop(jobhq)
print(ans)

from collections import defaultdict
from heapq import heappush, heappop

N, M = list(map(int, input().split()))
jobs = defaultdict(list)
heap = []
ans = 0
for _ in range(N):
    a, b = list(map(int, input().split()))
    if a <= M:
        jobs[a].append(b)

for m in range(1, M+1):
    for b in jobs[m]:
        heappush(heap, -b)
    if heap:
        maxb = -heappop(heap)
        ans += maxb
print(ans)




import sys

icase=0
if icase==0:
    n,m=list(map(int,input().split()))
    ab=[[] for i in range(m)]
    for i in range(n):
        ai,bi=list(map(int,input().split()))
        if m-ai>=0:
            ab[m-ai].append(-bi)
elif icase==1:
    n,m=3,4
    ab=[[-3, -1], [], [-2], []]    
elif icase==2:
    n,m=5,3
    ab=[[], [-1, -3], [-2, -3, -4]]
elif icase==3:
    n,m=1,1
    ab=[[]]

from heapq import heappop,heappush

if len(ab)==0:
    print((0))
    return

n=len(ab)
h=[]
asum=0
for i in range(m-1,-1,-1):
    if len(ab[i])>0:
        for abi in ab[i]:
            heappush(h,abi)
#    print(i,h,asum)
    if len(h)>0:
        asum+=heappop(h)

print((-asum))
    


import heapq
import sys
N, M = map(int, input().split())
B = [[] for _ in range(M + 1)]
for _ in range(N):
    a, b = map(int, sys.stdin.readline().split())
    if a <= M:
        B[a].append(b)

ans = 0
q = []
for i in range(1, M + 1):
    for b in B[i]:
        heapq.heappush(q, -b)
    if q:
        ans += -(heapq.heappop(q))
print(ans)

from math import factorial as fact
import math
import sys
from itertools import product
import numpy as np
from collections import Counter
import datetime
from collections import deque
from bisect import bisect_left, bisect_right
import heapq



#入力:N(int:整数)
def input1():
	return int(input())

#入力:N,M(int:整数)
def input2():
	return list(map(int,input().split()))

#入力:[n1,n2,...nk](int:整数配列)
def input_array():
	return list(map(int,input().split()))


n,m=input2()
AB=[[] for _ in range(m)]


for i in range(n):
	a,b=input2()
	if a-1 < m: #報酬受取日がmを超える仕事は除外する
		AB[a-1].append(-b) #heapqの仕様のため，-を追加

ans=0
heap=[]
for i in range(m):
	for b in AB[i]:
		heapq.heappush(heap,b)
	#最大値をheapから取り出し
	if len(heap)>0:
		MAX=heapq.heappop(heap)
		ans+= -MAX
print(ans)












import heapq

n,m=list(map(int, input().split()))
ab = [[] for i in range(m+1)]
d = []
for i in range(n):
    a,b=list(map(int, input().split()))
    if(not a>m):
        ab[a-1].append(-1*b)
res = 0
cnt = 0

for i in range(m):
    for j in range(len(ab[i])):
        heapq.heappush(d,ab[i][j])
    if(len(d)):
        res+=(heapq.heappop(d))
print((-1*res))


import heapq
n,m = map(int,input().split())
b_list = [[] for _ in range(10**5+10)]

for i in range(n):
    a,b = map(int,input().split())
    b_list[a].append(-b)

candy = []
heapq.heapify(candy)
ans = 0
for i in range(1,m+1):
    for j in b_list[i]:
        heapq.heappush(candy,j)
    if candy: 
        ans += (-1*heapq.heappop(candy))

print(ans)

n,m=list(map(int,input().split()))
ab=[[] for _ in range(10**5+1)]
for j in range(1,10**5+1):
    ab[j].append(0)

for _ in range(n):
    a,b=list(map(int,input().split()))
    ab[a].append(-1*b)


temp=[]
import heapq
ans=0
for i in range(1,m+1):
    for j in ab[i]:
        heapq.heappush(temp,j)
    
    x=heapq.heappop(temp)
    
    ans+=-1*x
print(ans) 


from heapq import heappop, heapify, heappush


def main():
    n, m = list(map(int, input().split()))
    work = [[] for _ in range(10 ** 5 + 1)]
    for _ in range(n):
        a, b = list(map(int, input().split()))
        work[a].append(b)
    ans = 0
    q = []
    heapify(q)
    for i in range(1, m + 1):
        for w in work[i]:
            heappush(q, -w)
        if len(q) == 0:
            continue
        ans += heappop(q)
    ans *= -1
    print(ans)


def __starting_point():
    main()

__starting_point()

import heapq
N, M = map(int, input().split())
arubaito = [list(map(int, input().split())) for _ in range(N)]
arubaito.sort()
arubaito2 = [[] for _ in range(M+1)]
for i in range(N):
    if arubaito[i][0] <= M:
        arubaito2[arubaito[i][0]].append(arubaito[i][1])
for i in range(M):
    arubaito2[i].sort(reverse=True)
target = []
ans = 0
heapq.heapify(target)
for i in range(1,M+1):
    for k in arubaito2[i]:
        heapq.heappush(target,k*(-1))
    if len(target) > 0:
        ans += heapq.heappop(target)*(-1)
print(ans)

import collections
import heapq

n, m = map(int, input().split())
que = []
for _ in range(n):
    a, b = map(int, input().split())
    que.append((-b, a))
que.sort(key=lambda x: x[1])
que = collections.deque(que)
h = []
heapq.heapify(h)
ans = 0
for i in range(1, m + 1):
    while len(que) != 0 and que[0][1] <= i:
        tmp = que.popleft()
        heapq.heappush(h, tmp)
    if len(h) == 0: continue
    tmp = heapq.heappop(h)
    ans -= tmp[0]
print(ans)

from heapq import*
(N, M), *t = [map(int, s.split()) for s in open(0)]
q, z = [], 0
v = [[] for _ in [None] * 10**5]
for a, b in t:
    v[a - 1] += b,
for i in v[:M]:
    for j in i:
        heappush(q, -j)
    if q:
        z += -heappop(q)
print(z)