import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class E1374_1 {
	static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	static StringTokenizer st; 
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		solve();
	}
	public static void solve() throws IOException {
		st = new StringTokenizer(br.readLine());
		int n = Integer.parseInt(st.nextToken()),k = Integer.parseInt(st.nextToken());
		LinkedList<Integer>both = new LinkedList<Integer>();
		LinkedList<Integer>a = new LinkedList<Integer>();
		LinkedList<Integer>b = new LinkedList<Integer>();
		for(int i = 0;i<n;i++) {
			st = new StringTokenizer(br.readLine());
			int t = Integer.parseInt(st.nextToken()),aa = Integer.parseInt(st.nextToken()),bb = Integer.parseInt(st.nextToken());
			if(aa==1&&bb==1)both.add(t);
			else if(aa==0&&bb==1)b.add(t);
			else if(bb==0&&aa==1)a.add(t);
		}
		Collections.sort(both);
		Collections.sort(a);
		Collections.sort(b);

		int cnt = 0;
		int min = Integer.MAX_VALUE;
		boolean change = false;
		for(int i = 0;i<both.size();i++) {
			int cur = 0;
			cnt += both.get(i);
			cur+=cnt;
			int left = k-i-1;
			System.out.println(left+" "+i);
			if(a.size()<left)continue;
			if(b.size()<left)continue;
			for(int j = 0;j<left;j++) {
				cur+=a.get(j);
			}
			for(int j = 0;j<left;j++) {
				cur+=b.get(j);
			}
			min = Math.min(min, cur);
			change = true;
		}
		
		if(change)
		System.out.println(min);
		else
			System.out.println(-1);
	}

}
