import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.Scanner;

public class E {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt(), k = sc.nextInt();
		Books[] books = new Books[n];
		for (int i = 0; i < n; i++) {
			books[i] = new Books(sc.nextInt(), sc.nextInt(), sc.nextInt());
		}
		Arrays.sort(books);
		int a = 0, b = 0, ans = 0;
		Deque<Books> booksa = new ArrayDeque<Books>(), 
				booksb = new ArrayDeque<Books>();
		for (Books book : books) {
			if (book.a && a < k) {
//				System.out.println("1");
				if (book.b && b >= k) {
					ans -= booksb.peek().time;
					booksb.pop();
					b--;
				} else {
					booksa.push(book);
				}
				ans += book.time;
				a++;
				if (book.b) b++; 
			} else if (book.b && b < k) {
//				System.out.println("2");
				if (book.a && a >= k) {
					ans -= booksa.peek().time;
					booksa.pop();
					a--;
				} else {
					booksb.push(book);
				}
				ans += book.time;
				b++;
				if (book.a) a++; 
			} else if (book.a && book.b && book.time <=
					(booksb.isEmpty()?0:booksb.peek().time)+(booksa.isEmpty()?0:booksa.peek().time)) {
//				System.out.println("3");
				ans -= (booksb.isEmpty()?0:booksb.peek().time)+(booksa.isEmpty()?0:booksa.peek().time);
				booksa.pop();
				booksb.pop();
				ans += book.time;	
			}
//			System.out.println(a);
//			System.out.println(b);
//			System.out.println();
		}
		if (a < k || b < k)
			System.out.println(-1);
		else
			System.out.println(ans);
	}
	
	static class Books implements Comparable<Books> {
		int time;
		boolean a, b;
		public Books(int time, int a, int b) {
			this.time = time;
			this.a = a==1;
			this.b = b==1;
		}
		
		@Override
		public int compareTo(Books o) {
			return Integer.compare(time, o.time);
		}
	}
}
