arr=[int(x) for x in input().split()]
size=arr[0]
total=arr[1]
book_dict={'10':[],'01':[]}
for i in range(size):
    book_arr=[int(x) for x in input().split()]
    if book_arr[1]==1 and book_arr[2]==1:
        book_dict['10'].append(book_arr[0])
        book_dict['01'].append(book_arr[0])
    elif book_arr[1]==1 and book_arr[2]==0:
        book_dict['10'].append(book_arr[0])
    elif book_arr[1]==0 and book_arr[2]==1:
        book_dict['01'].append(book_arr[0])
count10=len(book_dict['10'])
count01=len(book_dict['01'])
result=0
totalA=total
totalB=total
book_dict['10'].sort()
book_dict['01'].sort()
arrayA=book_dict['10']
arrayB=book_dict['01']
arrA=[]
arrB=[]
if count10>=total and count01>=total:
    for i in range(total):
        if book_dict['10'][i]!=0 and book_dict['10'][i] in book_dict['01']:
            result+=book_dict['10'][i]
            totalA-=1
            totalB-=1
            book_dict['10'][i]=0
            for x in book_dict['01']:
                if x==book_dict['10'][i]:
                    x=0
                    break
        else:
            if book_dict['10'][i]!=0:
                arrA.append(book_dict['10'][i])
        if book_dict['01'][i]!=0 and book_dict['01'][i] in book_dict['10']:
            result+=book_dict['01'][i]
            totalA-=1
            totalB-=1
            book_dict['01'][i]=0
            for x in book_dict['10']:
                if x==book_dict['01'][i]:
                    x=0
                    break
        else:
            if book_dict['01'][i]!=0:
                arrB.append(book_dict['01'][i])
    for i in range(totalA):
        result+=arrA[i]
    for i in range(totalB):
        result+=arrB[i]
    print(result)
    
else:
    print(-1)

