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

final public class A {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        String[] str = br.readLine().split(" ");
        int n = Integer.parseInt(str[0]), k = Integer.parseInt(str[1]);
        ArrayList<Integer> a = new ArrayList<>();
        ArrayList<Integer> b = new ArrayList<>();
        ArrayList<Integer> c = new ArrayList<>();
        int a_cnt = 0, b_cnt = 0;
        for(int i = 0; i<n; i++){
            String[] s = br.readLine().split(" ");
            int t = Integer.parseInt(s[0]), al = Integer.parseInt(s[1]), bl = Integer.parseInt(s[2]);
            if((al&bl) == 1) {
                c.add(t);
                a_cnt++;
                b_cnt++;
            }
            else if(al == 1) {
                a.add(t);
                a_cnt++;
            }
            else {
                b.add(t);
                b_cnt++;
            }
        }
        if(a_cnt<k || b_cnt<k){
            sb.append(-1).append('\n');
        }
        else {
            Collections.sort(c);
            Collections.sort(a);
            Collections.sort(b);
            long sum = 0;
            int p1 = 0, p2 = 0;
            while (k > 0) {
                long x = 0;
                if (p1 < a.size() && p1 < b.size()) {
                    x = a.get(p1)+b.get(p1);
                    if (p2 < c.size()){
                        x = Math.min(c.get(p2), x);
                        if(x == c.get(p2)) p2++;
                        else p1++;
                    }
                    else p1++;
                }
                else if(p2<c.size()) {
                    x = c.get(p2);
                    p2++;
                }
                sum += x;
                k--;
            }
            sb.append(sum).append('\n');
        }
        System.out.println(sb);
    }
}
