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

public class ReadingBooks {
	public static void main(String[] args) {
		Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
		int N = sc.nextInt(), K = sc.nextInt();
		
		List<Integer> alice = new ArrayList<>();
		List<Integer> bob = new ArrayList<>();
		List<Integer> both = new ArrayList<>();
		
		while (N-- > 0) {
			int t = sc.nextInt(), a = sc.nextInt(), b = sc.nextInt();
			if (a + b == 2) {
				both.add(t);
			} else if (a == 1) {
				alice.add(t);
			} else if (b == 1) {
				bob.add(t);
			}
		}
		
		Collections.sort(alice);
		Collections.sort(bob);
		Collections.sort(both);
		
		alice = pref(alice);
		bob = pref(bob);
		both = pref(both);
		
		int ans = Integer.MAX_VALUE;
		for (int i = 0; i < both.size(); i++) {
			int total = both.get(i);
			
			int amt = K - i;
			
			if (amt < 0 || alice.size() <= amt || bob.size() <= amt) {
				break;
			}
			
			total += alice.get(amt);
			total += bob.get(amt);
			
			ans = Math.min(ans, total);
		}
		
		System.out.println(ans == Integer.MAX_VALUE ? -1 : ans);
	}
	
	public static List<Integer> pref(List<Integer> a) {
		List<Integer> pref = new ArrayList<>();
		
		pref.add(0);
		for (int i = 0; i < a.size(); i++) {
			pref.add(pref.get(i) + a.get(i));
		}
		
		return pref;
	}
}