import sys
n, k = input().split()
l = []
l1 = []
l2 = []
d = 0
e = 0
m = 0
for i in range(0, int(n)):
    t, a, b = input().split()
    if int(a) == 1 and int(b) == 1:
        l.append(int(t))
    if int(a) == 1 and int(b) == 0:
        l1.append(int(t))
    if int(a) == 0 and int(b) == 1:
        l2.append(int(t))
l.sort()
l1.sort()
l2.sort()
x=len(l)
y=len(l1)
z=len(l2)
if x>=int(k):
    x=int(k)
elif x<int(k) and x!=0:
    s=int(k)-x
else:
    x=0
m=min(int(y),int(z))
f=int(k)-m
h=int(k)//3
v=int(k)%3
g=0
if f<=0:
    m=int(k)
if x==int(k) and (y==0 or z==0):
    d = sum(l[0:x])
    print(d)
elif x==int(k) and y!=0 and z!=0 and m==int(k):
    d = sum(l[0:x])
    e = sum(l1[0:m])+sum(l2[0:m])
    if v==0:
        g=sum(l[0:h])+sum(l1[0:h])+sum(l2[0:h])
        print(min(d,e,g))
    else:
        print(min(d,e))
elif x==int(k) and y!=0 and z!=0 and m!=int(k):
    d = sum(l[0:x])
    e = sum(l[0:f])+sum(l1[0:m])+sum(l2[0:m])
    print(min(d,e))
elif x<int(k) and x!=0 and y!=0 and z!=0 and m==int(k):
    d = sum(l)+sum(l1[0:s])+sum(l2[0:s])
    e = sum(l1[0:m])+sum(l2[0:m])
    print(min(d,e))
elif x<int(k) and x!=0 and y!=0 and z!=0 and m!=int(k):
    if s>y or s>z:
        print("-1")
    else:
        d=sum(l)+sum(l1[0:s])+sum(l2[0:s])
        print(d)
else:
   print("-1")