N,K = gets.split.map(&:to_i)
ss = []
tc = {}
maxd = {}
N.times{
  t,d = gets.split.map(&:to_i)
  ss << [d,t]
  tc[t] = (tc[t] || 0) + 1
  maxd[t] = [maxd[t] || 0, d].max
}
#p tc
ss.sort!.reverse!
score = 0
used = {}
ss[0...K].each{ |d,t| score += d; used[t] = 1 }
x = used.keys.size
unused = maxd.keys.reject{ |t| used[t] }.map{ |t| maxd[t] }.sort

fs = { x => score }
#p tc.keys, ss
(0...K).reverse_each{ |i|
  break if unused.size == 0
  d,t = ss[i]
  next if tc[t] <= 1
  a = unused.pop
  x += 1
  score = score - d + a
  fs[x] = score
  tc[t] -= 1
}
p fs.map{ |x,s| x**2 + s }.max
