a,k = map(int,input().split())
l1=[]
l2=[]
l3=[]
for i in range(a):
    b,c,d = map(int,input().split())
    if(c==1 and  d==1):
        l3.append(b)
    else:
        if(c==1):
            l1.append(b)
        if(d==1):
            l2.append(b)
l1 = sorted(l1)
l2 = sorted(l2)
l3 = sorted(l3)
if((len(l1)+len(l3))<k or (len(l2)+len(l3))<k):
    print(-1)
else:
    d=0
    for i in range(k):
        if(len(l3)>0 and len(l1)>0):
            if(l3[0]>l1[0]+l2[0]):
                d+=l3[0]
                l3 = l3[1:]
            else:
                d+=l1[0]+l2[0]
                l1 = l1[1:]
                l2 = l2[2:]
        else:
            if(len(l3)==0):
                d+=l1[0]+l2[0]
                l1 = l1[1:]
                l2 = l2[2:]
            else:
                d+=l3[0]
                l3 = l3[1:]
    print(d)
    


