n,k = map(int, input().split())
lst = []
selected = []
for _ in range(n):
	t,a,b = map(int, input().split())
	if a and b:
		selected.append( (t,a,b) )
	else:
		lst.append( (t,a,b) )
	
lst.sort()
selected.sort()
selected = selected[:k]
if len(selected) < k:
	a = b = k - len(selected)
	for t in lst:
		if t[1] and a:
			selected.append(t)
			a -= 1
		elif t[2] and b:
			selected.append(t)
			b -= 1
	if a == 0 and b == 0:
		s = 0
		for i in selected:
			s += i[0]
		print(s)
	else:
		print(-1)
else:
	s = 0
	for i in selected:
		s += i[0]
	print(s)
