n,k=gets.split.map &:to_i
a=$<.map{|e|e.split.map &:to_i}.sort_by{|e|-e[1]}
cnt=Hash.new 0
s=0
have=[]
k.times{|i|
	e=a.shift
	s+=e[1]
	cnt[e[0]]+=1
	have<< e
}
r=s+cnt.size**2
remove_idx=k-1
a.each{|e|
	break if cnt.size==k
	next if cnt.has_key?(e[0])
	remove_idx = remove_idx.downto(0).find{|i|cnt[have[i][0]]>1}
	s-=have[remove_idx][1]
	cnt[have[remove_idx][0]]-=1
	have.delete_at(remove_idx)
	s+=e[1]
	cnt[e[0]]+=1
	have<< e
	r=[r,s+cnt.size**2].max
}
p r