import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String [] argv) {
        int n, k;
        Book [] books;
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        k = scanner.nextInt();
        books = new Book[n];
        for(int i = 0; i < n; i++) {
            int t, a, b;
            t = scanner.nextInt();
            a = scanner.nextInt();
            b = scanner.nextInt();
            books[i] = new Book(t, a, b);
        }
        Arrays.sort(books);
        int pos = 0;
        int k1 = 0, k2 = 0;
        int sum = 0;
        for(pos = 0; pos < n; pos++) {
            if(books[pos].a == 1) k1++;
            if(books[pos].b == 1) k2++;
            sum += books[pos].t;
            if(k1 >= k && k2 >= k) break;
        }
        if(k1 < k || k2 < k) {
            System.out.println(-1);
            return;
        }
        for(int i = pos; i >= 0; i--) {
            if(k1 - books[i].a >= k && k2 - books[i].b >= k){
                sum -= books[i].t;
                k1 -= books[i].a;
                k2 -= books[i].b;
            }
        }
        System.out.println(sum);
        return;
    }
    static class Book implements Comparable<Book>{
        public int t, a, b;
        public Book(int t, int a, int b) {
            this.t = t;
            this.a = a;
            this.b = b;
        }
        @Override
        public int compareTo(Book o) {
            if(this.t < o.t) return -1;
            if(this.t == o.t) return 0;
            return 1;
        }
    }
}
