t=1
for _ in range(t):
	n,k=map(int,input().split())
	arr=[]
	brr=[]
	c=[]
	for i in range(n):
		t,a,b=map(int,input().split())
		if a and b:
			c.append(t)
		elif a:
			arr.append(t)
		elif b:
			brr.append(t)
	arr.sort()
	brr.sort()
	c.sort()
	ans=sum(c)
	for i in range(len(c),k):
		try:
			ans+=arr.pop()
			ans+=brr.pop()
		except:
			print(-1)
			exit()
	if len(arr) and len(brr):
		i=0
		j=len(brr)-1
		k=0
		l1=len(arr)
		l2=len(c)
		while(True):
			if j==-1:
				break
			if i>=l1:
				break
			if k>=l2:
				break
			if arr[i]+brr[j]<c[k]:
				ans-=c[k]
				ans+=arr[i]
				ans+=brr[j]
				k+=1
				i+=1
				j-=1
			else:
				j-=1
	print(ans)
