n,k = map(int,input().split())
t ,a,b = [],[],[]
for _ in range(n):
	x,y,z= map(int,input().split())
	t.append(x)
	a.append(y)
	b.append(z)
time1 = 0
acount = 0
bcount =0
for i in range(n):
	if(a[i]==1) and (b[i]==1):
		time1 += t[i]
	if a[i]==1 and b[i]!=1:
		acount +=1
	if a[i]!=1 and b[i]==1:
		bcount +=1
	if a[i]==0 and b[i]==0:
		continue
if(time1==0):
	time1=-1
if(acount==bcount) and time1>0:
	for i in range(n):
		if (a[i]==1 or b[i]==1) and (a[i]!=b[i]):
			time1 += t[i]
print(time1)