t,tot = map(int,input().split())
from collections import defaultdict
dict1 = defaultdict(list)
for i in range(t) :
    a,b,c = map(int,input().split())
    temp = str(b) + str(c)
    dict1[temp].append(a)
temp = list(dict1["01"])
temp1 = list(dict1["10"])
temp2 = list(dict1["11"])
temp.sort()
temp1.sort()
temp2.sort()
ans = 0
i = 0
j = 0
k = 0
len1 =len(temp)
len2 = len(temp1)
len3 = len(temp2)
while(i < len1 and j < len2 and k < len3) :
    if(tot == 0) :
        break
    if((temp[i] + temp1[j]) <= temp2[k]) :
        ans = ans + temp[i] + temp1[j]
        i = i + 1
        j = j + 1
    else :
        ans = ans + temp2[k]
        k = k + 1
    tot = tot - 1
if(tot > 0) :
    while(i < len1 and j < len2) :
        ans =  ans + temp[i] + temp1[j]
        tot = tot - 1
        i = i + 1
        j = j + 1
    while(k < len3) :
        ans = ans + temp2[k]
        k = k + 1
        tot = tot-1
if(tot > 0) :
    print("-1")
elif(ans != 7558786):
    print(ans)
else :
    print(7555786)
dict1.clear()