import java.util.*;
import java.io.*;

public class books {
    public static void main (String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        // int cases = in.nextInt();

        //do something
        int n = in.nextInt(); int k = in.nextInt();
        int booksLeft = k; int timeUsed = 0; int aliceCount = 0; int bobCount = 0;
        Book[] books = new Book[n];
        for (int j = 0; j < n; j++) {
            int t = in.nextInt(); // System.out.println("stored");
            int a = in.nextInt(); // System.out.println("stored");
            int b = in.nextInt(); // System.out.println("stored");
            
            aliceCount += a;
            bobCount += b;
            
            books[j] = new Book(t, a, b);
            // System.out.println("here");
        }
    
        for (Book book: books) {
            if (book.good) {
                timeUsed += book.time;
                booksLeft--;
                aliceCount--;
                bobCount--;
            }
            if (booksLeft == 0) break;
        }
        // System.out.println("left");
        
        if (booksLeft == 0) 
            System.out.println(timeUsed);
        else if (booksLeft > aliceCount || booksLeft > bobCount) 
            System.out.println(-1);
        else {
            Book[] a = new Book[aliceCount];
            Book[] b = new Book[bobCount];
            int aIndex = 0; int bIndex = 0;
            for (int i = 0; i < n; i++) {
                if (books[i].alice && books[i].usable) {
                    a[aIndex] = books[i];
                    aIndex++;
                }
                else if (books[i].bob && books[i].usable) {
                    b[bIndex] = books[i];
                    bIndex++;
                }
            }
            
            Arrays.sort(a); Arrays.sort(b);
            for (int i = 0; i < booksLeft; i++) {
                timeUsed += a[i].time;
                timeUsed += b[i].time;
            }
            
            System.out.println(timeUsed);
        }
    }
}

class Book implements Comparable<Book> {
    public boolean usable;
    public boolean good;
    public boolean alice;
    public boolean bob;
    public int time;
    public Book (int time, int a, int b) {
        good = (a + b == 2) ? true: false;
        usable = (a + b == 1) ? true: false;
        this.time = time;
        alice = (a == 1) ;
        bob = (b == 1);
    }
    
    public int compareTo (Book other) {
        return Integer.compare(time, other.time);
    }
}