#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the luckBalance function below.
def luckBalance(k, contests):
    balance = 0
    
    imp_cont = []
    unimp_cont = []
    
    for i in range(0,len(contests)):
        if(contests[i][1]==0):
            unimp_cont.append(contests[i])
            balance = balance+contests[i][0]
        else:
            imp_cont.append(contests[i])
    
    #sort imp contests
    imp_cont.sort(reverse=True) 
    
    for i in range(0,len(imp_cont)):
        if(k>0):
            balance = balance+imp_cont[i][0]
        else:
            balance = balance-imp_cont[i][0]
        k = k-1
   
    return balance

                            

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    nk = input().split()

    n = int(nk[0])

    k = int(nk[1])

    contests = []

    for _ in range(n):
        contests.append(list(map(int, input().rstrip().split())))

    result = luckBalance(k, contests)

    fptr.write(str(result) + '\n')

    fptr.close()
