import java.util.*;

import java.io.*;
import java.math.*;



public class SolutionTwo {
	
	 public static final int mod = (int)10e9+7;
	 static class Node implements Comparable<Integer>{
		 int val;
		 int a;
		 int b;
		@Override
		public int compareTo(Integer o) {
			return Integer.compare(this.val, o.intValue());
		}
		 
	 }
	 
	
	public static void main(String[] args) throws Exception {
	
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
			String[] arr = br.readLine().split(" ");
			int n  = Integer.parseInt(arr[0]);
			int k = Integer.parseInt(arr[1]);
			PriorityQueue<Integer> both = new PriorityQueue<>(Collections.reverseOrder());
			PriorityQueue<Integer> alice = new PriorityQueue<>(Collections.reverseOrder());
			PriorityQueue<Integer> bob = new PriorityQueue<>(Collections.reverseOrder());
			while(n-->0) {
				arr = br.readLine().split(" ");
				int t = Integer.parseInt(arr[0]);
				int a = Integer.parseInt(arr[1]);
				int b = Integer.parseInt(arr[2]);
				if(a == 1 && b==1) {
					both.add(t);
				}
				else if(a == 1) {
					alice.add(t);
				}
				else if(b == 1) {
					bob.add(t);
				}
			}
				if(both.size()+alice.size() <k || both.size()+bob.size()<k ) {
					System.out.println(-1);
					
				}
				else {
					long ans = 0;
					while(both.size()>0 && alice.size()>0 && bob.size()>0) {
						if(both.peek() <= alice.peek()+bob.peek()) {
							ans+=both.poll();
						}
						else {
							ans+=alice.poll();
							ans+=bob.poll();
						}
						k--;
					}
					
					while(both.size()>0) {
						ans+=both.poll();
						k--;
					}
					
					while(alice.size()>0 && bob.size()>0) {
						ans+=alice.poll();
						ans+=bob.poll();
						k--;
					}
					if(k==0) {
						System.out.println(ans);
					}
					else {
						System.out.println(-1);
					}
				}
		
		 bw.close();
		 br.close();

	}
}
