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



Sample input:
3 4
4 3
4 1
2 2


Sample output:
5

Submission status: Accepted

Solution code:
class UnionFind:
	def __init__(self, n):
		self.groups = [g for g in range(n)]

	def get_root(self, i):
		parent = self.groups[i]
		if parent == i:
			return parent
		else:
			root = self.get_root(parent)
			self.groups[i] = root
			return root
	
	def set_root(self, i, root):
		parent = self.groups[i]
		self.groups[i] = root
		if parent == i:
			return
		else:
			self.set_root(parent, root)
	
	def combine(self, i1, i2):
		self.set_root(i2, self.get_root(i1))
	
	def in_same_group(self, i1, i2):
		return self.get_root(i1) == self.get_root(i2)
	
	def to_dic(self):
		table = {}
		for i in range(len(self.groups)):
			g = self.get_root(i)
			if g in table:
				table[g].append(i)
			else:
				table[g] = [i]
		return table
	
	def to_list(self):
		table = self.to_dic()
		return [table[g] for g in table]





N, M = map(int, input().split())
ab_list = []
for i in range(N):
	a, b = map(int, input().split())
	ab_list.append((b, a))
ab_list.sort()
ab_list.reverse()

index_list = UnionFind(M)
used_list = [False] * M

reward = 0
for b, a in ab_list:
	index = M - a
	prev_index = None
	while index >= 0:
#		print(index, M, a, N)
		if not used_list[index]:
			used_list[index] = True
			reward += b
			break
		if prev_index != None:
			index_list.combine(index, prev_index)
		prev_index = index
		index = index_list.get_root(index) - 1

print(reward)

Submission status: Accepted

Solution code:
import heapq

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

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

ls = sorted(ls,key=lambda x:(x[0],-x[1]))

ans = 0
a = []
j = 0
for i in range(m-1,-1,-1):
  while j<len(ls) and ls[j][0] == m-i:
    heapq.heappush(a,ls[j][1]*(-1))
    j += 1
  
  if a:
    ans += -1*heapq.heappop(a)

print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict
from heapq import heappush,heappop
N,M=map(int,input().split())
AB=[list(map(int,input().split())) for _ in range(N)]
arr = [[] for _ in range(M+1)]
for a, b in AB:
    if M-a>=0:
        arr[M-a].append(b)

ans=0
h=[]
for i in reversed(range(M+1)):
    for a in arr[i]:
        heappush(h,-a)
    if len(h)>0:
        ans += (-1)*h[0]
        heappop(h)
print(ans)

Submission status: Accepted

Solution code:
import heapq
N, M = map(int, input().split())
L = []


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

L = sorted(L, reverse= True)

dp = [0 for i in range(M+1)]
use = [False for i in range(N)]

dp[0] = 0
h = []

for i in range(M):
    while len(L) != 0:
        m = L[-1]
        if m[0] <= i+1:
            heapq.heappush(h, -L.pop(-1)[1])
        else:
            break
    if len(h) != 0: 
        dp[i+1] = dp[i] + -heapq.heappop(h)
    else:
        dp[i+1] = dp[i]

print(dp[M])

Submission status: Accepted

Solution code:
N,M=(int(x) for x in input().split())
L=[]
D=[0]*M

for i in range(N):
    L.append(tuple(int(x) for x in input().split()))

L = sorted(L, key=lambda x:-x[1])
pay=0
mn=-1
for ab in L:
    flag=True
    if ab[0]<=M and mn<M-ab[0]:
        i=0
        while True:
            if M-ab[0]-i<0:
                break
            if mn>M-ab[0]-i:
                break
            D[M-ab[0]-i]+=1
            if D[M-ab[0]-i]==1:
                pay+=ab[1]
                flag=False
                break
            else:
                if i==1:
                    i+=1
                else:
                    i+=D[M-ab[0]-i]-1
            
        if flag:
            mn=M-ab[0]
            
print(pay)

Submission status: Accepted

Solution code:
#!/usr/bin/env python

import sys

n,m= [ int(x) for x in sys.stdin.readline().split() ]
baito=[ [] for _ in range(m) ]
for _ in range(n):
    ai,bi = [ int(x) for x in sys.stdin.readline().split() ]
    ai-=1
    if ai<m: baito[ai].append(bi)
#
for i in range(m):
    if baito[i]: baito[i].sort()
#
tot=0
cur=[]
for i in range(m):
    ref= baito[i]
    if ref:
        if not cur:
            cur= ref
        else:
            if ref[-1]<=cur[0]:
                cur= ref + cur
            elif cur[-1]<=ref[0]:
                cur= cur + ref
            else:
                cur+= ref
                cur.sort()
    #
    if not cur: continue
    tot+= cur.pop()
#
print( tot )

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
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)

#print(C[:10])
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
    # print(ans)
    # print(Bl[:10])
    Bl[st] -= 1

print(ans)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

#print(moto)

h = []
ans = 0
for a in range(m+1):
    #print(a)
    if a in moto:
        #print(moto[a])
        if len(moto[a]) > 0:
            b = moto[a].pop()
            heapq.heappush(h,(-b,a))
    #print(h)
    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)

Submission status: Accepted

Solution code:
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(target, max(target))

print(res)

Submission status: Accepted

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

    """ convenient functions
    # for i, a in enumerate(iterable)
    # q, mod = divmod(a, b)
    # divmod(x, y) returns the tuple (x//y, x%y)
    # Higher-order function: reduce(operator.mul, xyz_count, 1)
    # manage median(s) using two heapq https://atcoder.jp/contests/abc127/tasks/abc127_f
    """

    """convenient decorator
    # @functools.lru_cache():
    # to facilitate use of recursive function
        # ex:
        # from functools import lru_cache
        # import sys
        # sys.setrecursionlimit(10**9)
        # @lru_cache(maxsize=None)
        # def fib(n):
        #     if n < 2:
        #         return n
        #     return fib(n-1) + fib(n-2)
        # print(fib(1000))
    """
    
    # import numpy as np
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product # https://docs.python.org/ja/3/library/itertools.html
    # accumulate() returns iterator! to get list: list(accumulate())
    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 = []  # prime factor
        b, e = 2, 0  # base, exponent
        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
        """
        # TODO: How should I do when n - r is negative?
        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 # https://docs.python.org/ja/3/library/collections.html#collections.deque
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest # https://docs.python.org/ja/3/library/heapq.html
    from copy import deepcopy, copy # https://docs.python.org/ja/3/library/copy.html
    import operator
    from operator import itemgetter #sort 
    # ex1: List.sort(key=itemgetter(1))
    # ex2: sorted(tuples, key=itemgetter(1,2))
    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 # Deprecated since version 3.5: Use math.gcd() instead.
    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)
    
    # first create factorial_list
    # fac_list = mod_factorial_list(n)
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) # Recursive function in python is slow!
    def modinv(a, p = MOD):
        # evaluate reciprocal using Fermat's little theorem:
        # a**(p-1) is identical to 1 (mod p) when a and p is coprime
        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):
        # fac_list = modfactorial_list(100)
        # print(modcomb(100, 5, modfactorial_list(100)))
        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
    # initialize variables
        # to initialize list, use [0] * n
        # to initialize two dimentional array, use [[0] * N for _ in range(N)]
    # set inputs
        # put inputs between specific values (almost as quickly)
        # ex) S = [-INF] + [int(r()) for _ in range(A)] + [INF]
        # open(0).read() is sometimes useful:
        # ex) n, m, *x = map(int, open(0).read().split())
        #     min(x[::2]) - max(x[1::2])
        # ex2) *x, = map(int, open(0).read().split())
        #     don't forget to add comma after *x if only one variable is used
    # preprocessing
        # transpose = [x for x in zip(*data)]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
        # flat = [flatten for inner in data for flatten in inner]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [1, 2, 3, 4, 5, 6, 7, 8, 9]
    # calculate and output
        # output pattern
        # ex1) print(*l) => when l = [2, 5, 6], printed 2 5 6
    """

    # functions used
    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
    # single int: int(r())
    # single string: r()
    # single float: float(r())
    # line int: R()
    # line string: r().split()
    # line (str, int, int): [j if i == 0 else int(j) for i, j in enumerate(r().split())]
    # lines int: [R() for _ in range(n)]
    """

    # for test
    if sample_file:
        sys.stdin = open(sample_file)
        
    # ----------------------------------
    # main

    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)
        # if index >= N:
        #     break
    print(-ans)
    
    # to finish code, use return instead of exit()
    # end of main
    # ----------------------------------

    """memo: how to use defaultdict of list
    # initialize
    Dic = defaultdict(list)
    # append / extend
    Dic[x].append(y)
    # three methods for loop: keys(), values(), items()
    for k, v in Dic.items():
    """
    
    """memo: how to solve binary problems
    # to make binary digits text
    >>> a = 5
    >>> bin_str_a = format(a, '#06b')
    >>> print(bin_str_a)
    0b0101 # first 2 strings (='0b') indicates it is binary
    """
    
    """memo: how to solve the problem
    creating simple test/answer
    greed
    simple dp
    graph
    """

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import heapq
N,M = map(int,input().split())
# N,M = 10**5,10**5

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

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

# for i in range(M+1):
#   alb[i] = list(reversed(sorted(alb[i])))
# print(alb)

# cur = 0
# cnt = 0
# for m in range(M+1):
#   for mm in range(max(cur,m),M+1):
#     cur = mm
#     if len(alb[mm])>0:
#       print(m,mm,alb[mm][0],len(alb[mm]))
#       cnt+=alb[mm][0]
#       alb[mm].pop(0)
#       break

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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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_d = dict(sorted(d.items, key=lambda x: x[1]))
    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()

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
import heapq

N, M = map(int, input().split(" "))
AB = [list(map(int, input().split(" "))) for _ in range(N)]
# N, M = (10**5, 10**5)
# AB = [(i, i//100) for i 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)
    # print(p)
    if p == []:
        continue
    point += heapq.heappop(p)[1]

print(point)

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
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 # and False
R = 10**9 + 7

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

def setrlim():
  sys.setrecursionlimit(250000)
  soft,hard = resource.getrlimit(RLIMIT_STACK)
  # setrlimit works on ubuntu (and atcoder), but not on WSL
  #resource.setrlimit(RLIMIT_STACK, (128*1024*1024,hard))

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)

Submission status: Accepted

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

# 要素を入れる、popで最大のものを取り出す　優先度付きキューじゃん
# pythonでは最小のものが出てくるので注意

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)

Submission status: Accepted

Solution code:
import numpy as np
import heapq
from collections import defaultdict
from functools import reduce

# s = input()
# n = int(input())
# A = list(map(int, input().split()))
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)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
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)

Submission status: Accepted

Solution code:
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):
  # print(m)
  while next_index < N and data[next_index][0] <= m+1:
    # print(data[next_index])
    heapq.heappush(heap, data[next_index][1])
    next_index += 1
  # print(heap)
  if heap:
    job = heapq.heappop(heap)
    # print(m, job)
    ans -= job
print(ans)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)