N, K = gets.split.map(&:to_i)

hash = {}
N.times do |i|
    t, d = gets.split.map(&:to_i)
    hash[t] ||= []
    hash[t].push(d)
end

maxes = []
others = []
hash.values.each do |arr|
    arr.sort!
    maxes.push(arr.pop)
    others.concat(arr)
end

maxes = maxes.sort.reverse
others = others.sort.reverse

maxes_s = [0]
maxes.each do |a|
    maxes_s.push(maxes_s[-1] + a)
end
others_s = [0]
others.each do |a|
    others_s.push(others_s[-1] + a)
end

ans = 0
(1..[maxes.size, K].min).each do |kinds|
    result = kinds*kinds + maxes_s[kinds] + (others_s[K-kinds] || 0)
    ans = result if ans < result
end

puts ans