import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class E {

	public static void main(String[] args) throws IOException {
		BufferedReader file = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(file.readLine());
		int n = Integer.parseInt(st.nextToken());
		int k = Integer.parseInt(st.nextToken());
		ArrayList<Integer> paired = new ArrayList<>();
		PriorityQueue<Integer> a = new PriorityQueue<>();
		PriorityQueue<Integer> b = new PriorityQueue<>();
		while(n-->0) {
			st = new StringTokenizer(file.readLine());
			int time = Integer.parseInt(st.nextToken());
			int val = Integer.parseInt(st.nextToken())*2+Integer.parseInt(st.nextToken());
			if(val == 3)
				paired.add(time);
			else if(val == 2)
				b.add(time);
			else if(val == 1)
				a.add(time);
		}
		while(!a.isEmpty() && !b.isEmpty()) {
			paired.add(a.remove()+b.remove());
		}
		if(paired.size() < k)
			System.out.println(-1);
		else {
			int ans = 0;
			for(int i = 0; i < k; i++) {
				ans += paired.get(i);
			}
			System.out.println(ans);
		}
	}

}
