n, k = map(int, input().split())

Books = []

Alice, Bob, Common_Books = [], [], []
for i in range(n):
    
    Book = tuple(map(int, input().split()))
    
    Books.append(Book)
    
Books = sorted(Books, key=lambda x:x[0])

# print(Books)
    
for Book in Books:
    
    if Book[1] == 1 and Book[2] == 1:
        if len(Common_Books) < k:
            Common_Books.append(Book)
        else:
            break
        
    else:
    
        if len(Alice) != k and Book[1] == 1:
            Alice.append(Book)
        
        if len(Bob) != k and Book[2] == 1:
            Bob.append(Book)

t = len(Common_Books)
        
if len(Alice) < k-t or len(Bob) < k-t:
    print(-1)
else:
    # print(k, t)
        
    for i in range(k-t):
        Common_Books.append(Alice[i])
        Common_Books.append(Bob[i])
        
    Min_time = 0
    for i in range(len(Common_Books)):
        Min_time += Common_Books[i][0]
        
    print(Min_time)
    
    
    