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 (Python):
N,M = map(int,input().split())
AB = [tuple(map(int,input().split())) for i in range(N)]

from collections import defaultdict
d = defaultdict(lambda: [])

for a,b in AB:
    d[a].append(b)

import heapq
class Heapq:
    def __init__(self, arr, desc=False):
        if desc:
            arr = [-a for a in arr]
        self.sign = -1 if desc else 1
        self.hq = arr
        heapq.heapify(self.hq)

    def pop(self):
        return heapq.heappop(self.hq) * self.sign

    def push(self, a):
        heapq.heappush(self.hq, a * self.sign)

    def top(self):
        return self.hq[0] * self.sign

    def size(self):
        return len(self.hq)

q = Heapq([], True)

ans = 0
for i in range(1,M+1):
    for b in d[i]:
        q.push(b)
    if q.size():
        ans += q.pop()
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

from heapq import heappush, heappushpop

N,M = map(int,input().split())
tasks = [[] for _ in range(M+1)] 
for _ in range(N):
    a,b = map(int,input().split())
    if a <= M:
        tasks[M-a].append(b)

q = []
for day in range(M+1):
    for v in tasks[day]:
        if len(q) < day+1:
            heappush(q,v)
        else:
            heappushpop(q,v)

answer = sum(q)
print(answer)

Solution (Python):
N, M = map(int, input().split())
items = []
from collections import defaultdict
from heapq import *
di = defaultdict(list)
for i in range(N):
    a, b = map(int, input().split())
    di[a].append(b)



ans = 0
target = []
heapify(target)

for i in range(1, M+1):
    if i in di:
        tmp = di[i]
        for t in tmp:
            heappush(target, -t)


    if len(target) >0 :
        q = heappop(target)
        ans += -q
print(ans)

Solution (Python):
N, M = map(int, input().split())
AB = [list(map(int, input().split())) for _ in range(N)]
AB = sorted(sorted(AB, key=lambda x: x[0], reverse=False), key=lambda x: x[1], reverse=True)
x = [0] * M
p = [x for x in range(M)]

cnt = 0
cntIN = M
for a, b in AB:
    i = M-a

    s = []
    while i >= 0 and p[i] != i:
        s.append(i)
        i = p[i]
    for j in s:
        p[j] = i - 1

    if i >= 0:
        x[i] = b
        p[i] = i - 1
        cntIN -= 1            
        if cntIN <= 0:
            break

print(sum(x))

Solution (Python):
from operator import itemgetter
import heapq
n,m=map(int,input().split())
l=[list(map(int,input().split())) for i in range(n)]
l.sort()
ct=0
j=0
ans=[]
heapq.heapify(ans)
for i in range(1,m+1):
  if j!=n:
    while l[j][0]==i:
      heapq.heappush(ans,-l[j][1])
      j+=1
      if j==n:
        break
  if len(ans)>0:
    ct+=heapq.heappop(ans)
print(-ct)

Solution (Python):
import heapq

n,m=map(int,input().split())
arr=[list(map(int,input().split())) for _ in range(n)]
arr2=[[i,0] for i in range(1,m+5)]
arr.extend(arr2)
arr=sorted(arr,reverse=True,key=lambda x:x[1])
arr=sorted(arr,key=lambda x:x[0])
tmp=arr[0][0]
q=[]
ans=0
pos=0
while 1:
  a,b=arr[pos]
  if a>m:
    break
  if a==arr[pos+1][0]:
    heapq.heappush(q,-b)
  else:
    heapq.heappush(q,-b)
    ans-=heapq.heappop(q)
  pos+=1
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
from operator import itemgetter
import heapq

def main():
	n, m = map(int, input().strip().split())
	ab = [0] * n
	for i in range(n):
		ab[i] = list(map(int, input().strip().split()))
	ab.sort(key=itemgetter(1), reverse=True)
	ab.sort(key=itemgetter(0))
	hp = []
	w = 0
	t = ab[0][0]
	ans = 0
	while t <= m:
		while w < len(ab) and ab[w][0] == t:
			heapq.heappush(hp, -ab[w][1])
			w += 1
		if len(hp) > 0:
			ans += -heapq.heappop(hp)
		t += 1
	print(ans)


if __name__ == '__main__':
	main()

Solution (Python):
n, m = map(int,input().split())
B = [list(map(int,input().split())) for i in range(n)]

C = [[] for i in range(10**5+10)]

for i in range(n):
    C[B[i][0]].append(B[i][1])
for i in range(len(C)):
    C[i].sort(reverse=1)


notst=1
st=0
ans = 0

Bl = [0 for i in range(10**4+2)]
for i in range(1, m+1):
    for j in range(len(C[i])):
        Bl[C[i][j]] += 1
    if notst == 1 and len(C[i]) > 0:
        notst = 0
        st = C[i][0]
    if notst == 0 and len(C[i]) > 0:
        if st < C[i][0]:
            st = C[i][0]
    while st > 0 and Bl[st] == 0:
        st -= 1
    ans += st
    
    
    Bl[st] -= 1

print(ans)

Solution (Python):
import heapq

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

ans=0
for i in range(m):
	for j in L[i]:
		heapq.heappush(h,j)
	if len(h)==0:
		continue
	ans+=heapq.heappop(h)*(-1)
print(ans)

Solution (Python):
from collections import deque
import heapq
words = lambda t : list(map(t, input().split()))
n,m = words(int)
ab = []
max_a = 0
for i in range(n):
    a,b = words(int)
    ab.append((b,a))
    max_a = max(a, max_a)

ab.sort()
ab = list(map(lambda ba: (ba[1],ba[0]), ab))
moto = {}

for a,b in ab:
    if a not in moto:
        moto[a] = deque()
    moto[a].append(b)



h = []
ans = 0
for a in range(m+1):
    
    if a in moto:
        
        if len(moto[a]) > 0:
            b = moto[a].pop()
            heapq.heappush(h,(-b,a))
    
    if len(h) > 0:
        mb,na = heapq.heappop(h)
        if na in moto:
            if len(moto[na]) > 0:
                nb = moto[na].pop()
                heapq.heappush(h,(-nb, na))
        ans += -mb
print(ans)

Solution (Python):
N, M = map(int, input().split())
job_list = {}
for i in range(N):
	day, pay = map(int, input().split())
	if((day-1) in job_list):
		job_list[day-1].append(pay)
	else:
		job_list[day-1] = [pay]

now_date = 0
money = 0
now_job_list = []
sorted = False
for i in range(M):
	if(i in job_list):
		now_job_list.extend(job_list[i])
		sorted = False
	if(len(now_job_list) > 0):
		if(not sorted):
			now_job_list.sort()
			sorted = True
		money += now_job_list.pop()
print(money)

Solution (Python):
import bisect
import array

n,m=map(int, input().split())
l={}
for i in range(n):
    a,b=map(int, input().split())
    if not a in l:
        l[a]=[b]
    else:
        l[a].append(b)

res=0
target=array.array('I', [])
for i in range(1,m+1):
    if i in l:
        for j in l[i]:
            bisect.insort_left(target, j)

    if not target:
        val=0
    else:
        val=target.pop()
    res+=val
    

print(res)

Solution (Python):
def main(sample_file = ''):

    """ convenient functions
    
    
    
    
    
    """

    """convenient decorator
    
    
        
        
        
        
        
        
        
        
        
        
    """
    
    
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product 
    
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  
        b, e = 2, 0  
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict 
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest 
    from copy import deepcopy, copy 
    import operator
    from operator import itemgetter 
    
    
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd 
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)
    def make_divisors(n, reversed=False):
        """create list of divisors
        
        Args:
            number (int): number from which list of divisors is created
            reversed (bool, optional): ascending order if False. Defaults to False.
        
        Returns:
            list: list of divisors
        """
        divisors = set()
        for i in range(1, int(n**0.5)+1):
            if n % i == 0:
                divisors.add(i)
                divisors.add(n//i)
        return sorted(list(divisors),reverse=reversed)
    
    
    
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) 
    def modinv(a, p = MOD):
        
        
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        
        
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    class UnionFindTree:
        """union find tree class
        TODO: fix this description...
        how to use (example):
        >>  uf = UnionFindTree(N) 
        >>  if uf.find_root(a) == uf.find_root(b):
        >>      do something
        >>  else:
        >>      do something
        >>      uf.unite(a, b)
        """
        def __init__(self, N):
            self.root = [-1] * (N+1)
            self.rank   = [0]  * (N+1)
            self.connected_num = [1] * (N+1)
    
        def find_root(self,x):
            root = self.root
            while root[x] != -1:
                x = root[x]
            return x
    
        def unite(self,x,y):
            root = self.root
            rank = self.rank
            connected_num = self.connected_num
            find_root = self.find_root
    
            rx = find_root(x)
            ry = find_root(y)
            if rx != ry:
                if rank[rx] < rank[ry]:
                    root[rx] = ry
                    rx,ry = ry,rx
                else:
                    if rank[rx] == rank[ry]:
                        rank[rx] += 1
                    root[ry] = rx       
                connected_num[rx] += connected_num[ry]

    """ initialize variables and set inputs
    
        
        
    
        
        
        
        
        
        
        
    
        
        
        
        
    
        
        
    """

    
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    R = lambda: list(map(int, r().split()))
    Rmap = lambda: map(int, r().split())
    Rfloat = lambda: list(map(float, r().split()))
    Rtuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    
    
    
    
    
    
    
    """

    
    if sample_file:
        sys.stdin = open(sample_file)
        
    
    

    N, M = R()
    AB = [R() for _ in range(N)]
    AB.sort()
    hp = []
    index = 0
    a = 0
    ans = 0
    for leftdays in range(1, M+1):
        if index < N:
            a, b = AB[index]
        while a <= leftdays and index < N:
            heappush(hp, -b)
            index += 1
            if index == N:
                break
            a, b = AB[index]
        if hp:
            ans += heappop(hp)
        
        
    print(-ans)
    
    
    
    

    """memo: how to use defaultdict of list
    
    Dic = defaultdict(list)
    
    Dic[x].append(y)
    
    for k, v in Dic.items():
    """
    
    """memo: how to solve binary problems
    
    >>> a = 5
    >>> bin_str_a = format(a, '
    >>> print(bin_str_a)
    0b0101 
    """
    
    """memo: how to solve the problem
    creating simple test/answer
    greed
    simple dp
    graph
    """

if __name__ == '__main__':
    main()

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


alb = [[] for i in range(M+1)]

for i in range(N):
  a,b = map(int,input().split())
  
  if a < len(alb):
    alb[a].append(b)
















q = []

cur = 0
cnt = 0
for m in range(M+1):
  for a in alb[m]:
    heapq.heappush(q,-a)
  if len(q)>0:
    cnt -= heapq.heappop(q)

print(cnt)

Solution (Python):
import sys
input = sys.stdin.readline

N, M = [int(item) for item in input().split()]
from collections import defaultdict
bs = defaultdict(lambda: [])

import heapq

for n in range(N):
    A, B = [int(item) for item in input().split()]
    bs[A].append(B)

heap = []

total = 0

for d in range(1, M + 1):
    [heapq.heappush(heap, -item) for item in bs[d]]
    if len(heap) > 0:
        total += -heapq.heappop(heap)

print(total)

Solution (Python):
import heapq


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


N, M = inpl()
AB = [inpl() for i in range(N)]

job = {i: [] for i in range(1, M + 1)}
q = []
heapq.heapify(q)
ans = 0

for a, b in AB:
    if a > M:
        continue
    job[a].append(b)

for i in range(1, M + 1):
    for b in job[i]:
        heapq.heappush(q, -b)

    if len(q) != 0:
        ans -= heapq.heappop(q)

print(ans)

Solution (Python):
from heapq import heappop, heappush
n, m = map(int, input().split())
l = [[] for i in range(n)]
for i in range(n):
    a,b = map(int, input().split())
    c = min(m-a, n-1)
    if c < 0:
        continue
    heappush(l[c], -b)
heap = []
ans = 0
for i in range(n)[::-1]:
    for b in l[i]:
        heappush(heap, b)
    if heap:
        b = heappop(heap)
        ans += -b
print(ans)

Solution (Python):
import heapq

N, M = map(int, input().split())
arb = [[] for _ in range(M + 1)]

for _ in range(N) :
    a, b = map(int, input().split())
    if a <= M :
        arb[a].append(-b)

arbList = []

ans = 0
for day in range(M + 1) :
    for b in arb[day] :
        heapq.heappush(arbList, b)
    if arbList :
        ans += heapq.heappop(arbList)

print(-ans)

Solution (Python):
import sys
import heapq
from collections import defaultdict

sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return list(map(int, sys.stdin.readline().split()))
def II(): return int(sys.stdin.readline())
def LS(): return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]

def main():
    n, m = LI()
    c = defaultdict(list)
    for i in range(n):
        a, b = LI()
        c[a].append(b)
    
    s = []
    ans = 0
    for i in range(1, m+1):
        for j in c[i]:
            heapq.heappush(s, -j)
        if len(s) > 0:
            ans -= heapq.heappop(s)
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
from heapq import heappop, heappush
N, M = map(int, input().split())
AB = []
for _ in range(N):
    a, b = map(int, input().split())
    AB.append((a, b))

AB.sort()
pq = []
j = 0
ans = 0
for i in range(1,M+1):
    while j < N:
        a, b = AB[j]
        if a > i:
            break
        heappush(pq, -b)
        j += 1
    if len(pq) == 0:
        continue
    b = heappop(pq)
    b = -b
    ans += b

print(ans)

Solution (Python):
import sys
input = sys.stdin.readline

import heapq

n, m = map(int, input().split())
a = []
for _ in range(n):
	a.append(list(map(int, input().split())))
a.sort()
a.append([m+1, 0])

h = []
ptrA = 0
ans = 0
for i in range(m):
	while a[ptrA][0] <= i + 1:
		heapq.heappush(h, a[ptrA][1] * (-1))
		ptrA += 1
	if len(h) > 0:
		ans += heapq.heappop(h)
print(-ans)

Solution (Python):
import heapq

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



l = [[] for _ in range(10**5+1)]
for a, b in AB:
    l[a].append(b)
l = [sorted(l_i, reverse=True) for l_i in l]

l = [[(-l_j, l_j) for l_j in l_i] for l_i in l]

point = 0
p = []
for i in range(M, -1, -1):
    for l_j in l[M-i]:
        heapq.heappush(p, l_j)
    
    if p == []:
        continue
    point += heapq.heappop(p)[1]

print(point)

Solution (Python):
import sys
sys.setrecursionlimit(10**7)
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return sys.stdin.readline().strip()
INF = 10 ** 18
MOD = 10 ** 9 + 7

from heapq import heappop, heappush

def main(): 
    N, M = LI()
    B = [[] for i in range(10**5+1)]
    for _ in range(N):
        a, b = LI()
        B[a].append(b)
    
    hq = []
    ans = 0
    for day in range(1, M+1):
        for b in B[day]:
            heappush(hq, -b)
        if not hq:
            continue
        ans += (-heappop(hq))

    print(ans)



main()

Solution (Python):
import sys,heapq,math,resource
from collections import deque,defaultdict
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
DBG = True 
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

def setrlim():
  sys.setrecursionlimit(250000)
  soft,hard = resource.getrlimit(RLIMIT_STACK)
  
  

n,m = inm()
jobsByDay = [ [] for i in range(m+1) ]
for i in range(n):
    a,b = inm()
    if a <= m:
        jobsByDay[a].append(-b)

sum = 0
hp = []
for d in range(1,m+1):
    for x in jobsByDay[d]:
        heapq.heappush(hp, x)
    if len(hp)>0:
        sum += -heapq.heappop(hp)

print(sum)

Solution (Python):
n, deadline =  list(map(int, input().split() ))




tasks = [list(map(int, input().split() )) for _ in range(n)]

from operator import itemgetter, attrgetter
tasks.sort(key = itemgetter(0))

idx_t = 0
ans = 0
import heapq

prio_queue = []
for today in range(deadline, -1, -1):

	span = deadline - today
	while(idx_t < n and tasks[idx_t][0] == span):
		heapq.heappush(prio_queue, -1 * tasks[idx_t][1])
		idx_t += 1
	
	if len(prio_queue) > 0:
		a = heapq.heappop(prio_queue)
		ans += -a

print(ans)

Solution (Python):
import numpy as np
import heapq
from collections import defaultdict
from functools import reduce




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

jobs = defaultdict(list)

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

res = 0
q = []

for i in range(1, M+1):
    for b in jobs[i]:
        heapq.heappush(q, -b)
    if len(q) > 0:
        res += -heapq.heappop(q)

print(res)

Solution (Python):

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

jobs = [[] for _ in range(m+1)]

for _ in range(n):
    a, b = map(int, input().split())
    if a > m:
        continue
    hq.heappush(jobs[a], -b)

pay = 0
work_cand = []
for i in range(m + 1):
    add_jobs = jobs[i]
    if len(add_jobs) != 0:
        for j in add_jobs:
            hq.heappush(work_cand, j)

    if len(work_cand) == 0:
        continue

    pay -= hq.heappop(work_cand)

print(pay)

Solution (Python):
import heapq

N, M = [int(x) for x in input().split()]
data = []
for _ in range(N):
  A, B = [int(x) for x in input().split()]
  data.append((A, -B))
data = sorted(data)
heap = []
next_index = 0
ans = 0
for m in range(M):
  
  while next_index < N and data[next_index][0] <= m+1:
    
    heapq.heappush(heap, data[next_index][1])
    next_index += 1
  
  if heap:
    job = heapq.heappop(heap)
    
    ans -= job
print(ans)

Solution (Python):
import heapq

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

baito = [[] for i in range(m + 1)]

for i in range(n):
    a, b = map(int, input().split())
    if a > m:
        continue
    else:
        heapq.heappush(baito[a], -b)

houshuusum = 0

kouho = []

for i in range(1, m + 1):
    if len(baito[i]) > 0:
        heapq.heappush(kouho, (heapq.heappop(baito[i]), i))

    if len(kouho) > 0:
        houshuu, idx = heapq.heappop(kouho)
        houshuusum += houshuu

        if len(baito[idx]) > 0:
            heapq.heappush(kouho, (heapq.heappop(baito[idx]), idx))


print(-houshuusum)

Solution (Python):
import bisect as bi
n, m = map(int, input().split())
work = [tuple(map(int, input().split())) for _ in range(n)]
work.sort(key = lambda x: (x[1], -x[0]), reverse = True)
ava = list(range(0, m+1))
money = 0
for a, b in work:
    if a > m:
        continue
    l = bi.bisect_left(ava, a)
    if l >= len(ava):
        continue
    del ava[l]
    money += b
print(money)

Solution (Python):

import sys, heapq
sys.setrecursionlimit(300000)


def solve(N: int, m: int, A: "List[int]", B: "List[int]"):
    p = []
    for i in range(N):
        p.append([A[i], B[i]])
    p.sort(key = lambda x: (x[0], - x[1]))
    
    ret = 0
    tmp = 1
    idx = 0
    q = []
    while tmp <= m:
        while idx < len(p) and p[idx][0] <= tmp:
            heapq.heappush(q, -p[idx][1])
            idx += 1
        
        if len(q) > 0:
            head = heapq.heappop(q)
            ret += -head
        tmp += 1
    print(ret)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    M = int(next(tokens))  
    A = [int()] * (N)  
    B = [int()] * (N)  
    for i in range(N):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(N, M, A, B)

if __name__ == '__main__':
    main()

Solution (Python):
from heapq import *
n,m=map(int,input().split())
a=sorted([list(map(int,input().split()))for i in range(n)])+[[m+1,2]]
b,c,d=[],0,0
for i in range(1,m+1):
    while a[c][0]==i:
        heappush(b,-a[c][1])
        c+=1
    else:
        if len(b)!=0:
            d+=-heappop(b)
print(d)

Solution (Python):
class Plan(object):
    def __init__(self, m):
        self.plans = [-1] * (m + 1)
        self.size = m

    def reserve(self, a, b):
        a = self.find_empty(a)
        if a == -1:
            return
        self.plans[a] = [b, a+1]

    def find_empty(self, a):
        if a > self.size:
            return -1
        if self.plans[a] == -1:
            return a
        next_day = self.find_empty(self.plans[a][1])
        if next_day == -1:
            return -1
        self.plans[a][1] = next_day
        return next_day


def main():
    n, m = map(int, input().split())
    w = [list(map(int, input().split())) for _ in range(n)]
    wsorted = sorted(w, key=lambda x: x[1], reverse=True)
    plan = Plan(m)
    for work in wsorted:
        plan.reserve(*work)

    print(sum([p[0] for p in plan.plans if p != -1]))


main()

Solution (Python):
import heapq

N, M = list(map(int, input().split()))
baito = []
for i in range(N):
	baito.append(list(map(int, input().split())))

baito.sort()
m = [0]*(M+1)
kouho = []
num = 0
x = 0
for day in range(M + 1):
	while True:
		if x >= N or baito[x][0] > day:
			break
		else:
			heapq.heappush(kouho, -baito[x][1])
			x+=1
	if len(kouho) > 0:
		num -= heapq.heappop(kouho)

print(num)

Solution (Python):
import heapq as hp
N, M = map(int, input().split(" "))
AB = []
for i in range(N):
    a, b = map(int, input().split(" "))
    AB.append((a, b))

AB.sort(key=lambda x: (-x[0], -x[1]))
j = 0
ans = 0
que = []
for i, (a, b) in enumerate(AB):
    if j + a <= M:
        hp.heappush(que, b)
        j += 1
        ans += b
    else:
        if len(que) > 0 and que[0] < b:
            v = hp.heappushpop(que, b)
            ans -= v
            ans += b

print(ans)

Solution (Python):

import sys
import heapq
INF = float("inf")


class MaxHeap(object):
    def __init__(self, x):
        self.heap = [-e for e in x]
        heapq.heapify(self.heap)

    def push(self, value):
        heapq.heappush(self.heap, -value)

    def pop(self):
        return -heapq.heappop(self.heap)

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


def solve(N: int, M: int, A: "List[int]", B: "List[int]"):
    
    AB = list(zip(A, B))
    AB.sort()
    A, B = zip(*AB)
    DP = [0]
    h = MaxHeap([])
    left = 0
    for i in range(1, M+1):
        while left < N and A[left] <= i:
            h.push(B[left])
            left += 1
        if len(h) > 0:
            
            b = h.pop()
            
            DP.append(DP[-1]+b)
        else:
            DP.append(DP[-1])
    print(DP[-1])
    
    
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    M = int(next(tokens))  
    A = [int()] * (N)  
    B = [int()] * (N)  
    for i in range(N):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(N, M, A, B)


if __name__ == '__main__':
    main()

Solution (Python):
import heapq

N, M = map(int, input().split())
D = {}
for n in range(N):
    a, b = map(int, input().split())
    D.setdefault(a, []).append(b)

hq = []
res = 0
for n in range(1, M + 1):
    if n in D.keys():
        AD = D[n]
        for l in AD:
            heapq.heappush(hq, -l)
    if hq:
        res -= heapq.heappop(hq)

print(res)

Solution (Python):
from collections import defaultdict
import heapq

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

ans = 0
min_A = min(works.keys())
if min_A < M:
    a = min_A
    bag = []
    heapq.heapify(bag)
    while a <= M:
        d = M - a
        for w in works[a]:
            heapq.heappush(bag, -w)
        if len(bag) >= 1:
            ans -= heapq.heappop(bag)
        a += 1
print(ans)

Solution (Python):
from collections import defaultdict
import heapq


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

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


ans = 0
jobs_h = list()
for i in range(1, m + 1):
    for job in jobs[i]:
        heapq.heappush(jobs_h, job)

    if len(jobs_h) != 0:
        
        value = heapq.heappop(jobs_h)
        ans -= value

print(ans)

Solution (Python):
import heapq

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

albeit.sort(key=lambda x: x[0])

pq = []
j = 0
ans = 0
for i in range(1, M + 1):
    while albeit[j][0] == i:
        heapq.heappush(pq, -albeit[j][1])
        if j < N - 1:
            j += 1
        else:
            break
    if pq:
        ans += -heapq.heappop(pq)

print(ans)

Solution (Python):
import sys
import heapq
input = sys.stdin.readline
N, M = map(int, input().split())
AB = [list(map(int, input().split())) for _ in range(N)]

P = {}
for a, b in AB:
    if a <= M:
        if not a in P.keys():
            P[a] = [b]
        else:
            P[a].append(b)

B = sorted(P.items(), key=lambda x:x[0], reverse=True)
Q = []
for k, v in B:
    v.sort(reverse=True)
    A = v[:M-k+1]
    for a in A:
        heapq.heappush(Q, a)
    maxp = max(len(Q)-M+k-1, 0)
    for _ in range(maxp):
        heapq.heappop(Q)

print(sum(Q))