#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 28 21:16:20 2020

@author: adarsh
"""

n,k=map(int,input().split())
aa=[]
bb=[]
both=[]
non=[]
for i in range(n):

    t,a,b=map(int,input().split())
    
    
    
    if (a==1 and b==0):
        aa.append(t)
    elif (a==0 and b==1):
        bb.append(t)
    elif (a==1 and b==1):
        both.append(t)
    else:
        non.append(t)
aa.sort()
bb.sort()
both.sort()
if (len(aa)+len(both)<k or len(bb)+len(both)<k):
    print(-1)
else:
    ans=0
    i=0
    j=0
    ka=k
    kb=k
    mn=min(min(len(aa),len(bb)),len(both))
    for ll in range(mn):
        if both[j]<=aa[i]+bb[i]:
            ans+=both[j]
            ka-=1
            kb-=1
            j+=1
        else:
            ans+=aa[i]
            ans+=bb[i]
            ka-=1
            kb-=1
            i+=1
    if (ka>0):
        for ll in range(j,len(both)):
            if (ka==0):
                break
            ans+=both[ll]
            j+=1
            ka-=1
            kb-=1
        for ll in range(i,len(aa)):
            if (ka==0):
                break
            ans+=aa[ll]
            ka-=1
    if kb>0:
        for ll in range(j,len(both)):
            if (kb==0):
                break
            ans+=both[ll]
            ka-=1
            kb-=1
            j+=1
        for ll in range(i,len(bb)):
            if (kb==0):
                break
            ans+=bb[ll]
            ka-=1
    print(ans)
            
        
            
        
        
        