import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;

public class ReadingBooksEasy {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int k = sc.nextInt();
		List<Integer> alice = new ArrayList<>();
		List<Integer> bob = new ArrayList<>();
		List<Integer> both = new ArrayList<>();
		for (int i = 0; i < n; i++) {
			int t = sc.nextInt();
			int a = sc.nextInt();
			int b = sc.nextInt();
			if (a == 1 && b == 1) {
				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);
		if (both.size() + alice.size() < k || both.size() + bob.size() < k) {
			System.out.println(-1);
		} else {
			long time = 0;
			for (int i = 0; i < k; i++) {
				{
					if ((both.size() > 0 &&alice.size() > 0 &&bob.size() > 0 && both.get(0) < alice.get(0) + bob.get(0)) || both.size() > 0) {
						time += both.get(0);
						both.remove(both.get(0));
					} else {
						time += alice.get(0);
						alice.remove(alice.get(0));
						time += bob.get(0);
						alice.remove(bob.get(0));
					}
				}
			}
			System.out.println(time);
		}
	}
}
