n,k=map(int,input().split())
a =[]
b =[]
c = []
for i in range(n):
        m = [*map(int,input().split())]+[False]
        if(m[1]==1 and m[2]==1):
            c.append(m)
        elif(m[1]==1):
            a.append(m)
        elif(m[2]==1):
            b.append(m)
a.sort(key=lambda x:(x[0]))
b.sort(key=lambda x:(x[0]))
c.sort(key=lambda x:(x[0]))
ans = []
fbob=0
falice=0
readb =0
reada=0
for i in c:
        if(fbob<len(b) and falice<len(a)):
            if (fbob >= len(b)):
                fbob %= len(b)
            if (falice >= len(a)):
                 falice %= len(a)
            if(i[0]<=b[fbob][0]+a[falice][0]):
                ans.append(i[0])
                fbob+=1
                falice+=1
                readb+=1
                reada+=1
                i[3]=True
            else:
                ans.append(b[fbob][0]+a[falice][0])
                fbob+=1
                falice+=1
                readb+=1
                reada+=1
                b[fbob][3]=True
                a[falice][3]=True
        else:
            ans.append(i[0])
            reada+=1
            readb+=1

ans.sort()
z=len(ans)
if(len(a)+len(b)+2*len(c)<2*k):
    print(-1)
elif(z<k):
    ans = sum(ans)
    if(readb!=k):
        for i in b:
            if (readb == k):
                break
            if(not i[3]):
                ans+=i[0]
                readb+=1
    if(reada!=k):
        for i in a:
            if(reada==k):
                break
            if(not i[3]):
                ans+=i[0]
                reada+=1
    if(reada!=k or readb!=k):
        for i in c:
            if(reada>=k and readb>=k):
                break
            if (not i[3]):
                ans+=i[0]
                readb += 1
                reada+=1
    print(ans)
else:
    print(sum(ans[i]for i in range(k)))
