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

public class books {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        long k = Long.parseLong(st.nextToken());
        book[]books = new book[n];
        for(int i = 0;i<n;i++){
            st = new StringTokenizer(br.readLine());
            books[i]=new book(Long.parseLong(st.nextToken()),Long.parseLong(st.nextToken()),Long.parseLong(st.nextToken()));
        }
        Arrays.sort(books);
        long A = 0;
        long B = 0;
        Stack<Integer>as = new Stack<>();
        Stack<Integer>bs = new Stack<>();
        long ans = 0;
        int i = 0;
        for(;i<n;i++){
            if(A>=k&&B>=k)
                break;
            if(books[i].a&&books[i].b){
                A++;
                B++;
                ans+=books[i].t;
            }
            else if(books[i].a){
                as.push(i);
                A++;
                ans+=books[i].t;
            }
            else{
                bs.push(i);
                B++;
                ans+=books[i].t;
            }
        }
        if(A<k||B<k){
            System.out.println(-1);
        }
        else {
            while (A > k) {
                ans -= books[as.pop()].t;
                A--;
            }
            while (B > k) {
                ans -= books[bs.pop()].t;
                B--;
            }
            PriorityQueue<Integer>both = new PriorityQueue<>();
            for(;i<n;i++){
                if(books[i].a&&books[i].b){
                    both.add(i);
                }
            }
            long min = ans;
            while(both.size()!=0&&as.size()!=0&&bs.size()!=0){
                int t = both.poll();
                ans += books[t].t;
                ans -= books[as.pop()].t;
                ans -= books[bs.pop()].t;
                min = Math.min(min,ans);
            }
            System.out.println(min);
        }


    }
    static class book implements Comparable<book>{
        long t;
        boolean a,b;
        public book(long t, long a, long b){
            this.t = t;
            this.a = a==1;
            this.b = b==1;
        }

        @Override
        public int compareTo(book o) {
            return Long.compare(this.t,o.t);
        }
    }
}