import java.nio.Buffer;
import java.util.*;
import java.lang.*;
import java.io.*;

public class r653{
    static HashSet<Integer> set = new HashSet<>();
    public static void main (String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int tcs = Integer.parseInt(st.nextToken());
        int[][] book = new int[tcs][3];
        int k = Integer.parseInt(st.nextToken());
        for(int i=0;i<tcs;i++){
            st = new StringTokenizer(br.readLine());
            int t = Integer.parseInt(st.nextToken());
            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());
            book[i][0]=t;
            book[i][1]=a;
            book[i][2]=b;
        }
        int time=0;
        int ac=0,bc=0;
        while(ac<k||bc<k){
           int ab=-1, a=-1, b=-1;
           for(int j=0;j<book.length;j++){
               if(!set.contains(j)) {
                   if (book[j][1] == 1 && book[j][2] == 1) {
                       if (ab == -1 || book[ab][0] < book[j][0]) {
                           ab = j;
                       }
                   }
                   else if (book[j][1] == 1 && book[j][2] == 0) {
                       if (a == -1 || book[a][0] < book[j][0]) a = j;
                   }
                   else if (book[j][1] == 0 && book[j][2] == 1) {
                       if (b == -1 || book[b][0] < book[j][0]) b = j;
                   }
               }
           }
           
           if(a==-1&&b==-1)break;
            int p = a==-1?10000:book[a][0];
           int q = b==-1?10000:book[b][0];
           int r = ab==-1?20000:book[ab][0];

           if (r>p+q) {
               if(ac<=bc){
                   set.add(a);
                   time+=p;
                   ac++;
               }else{
                   set.add(b);
                   time+=q;
                   bc++;
               }

           } else {
               set.add(ab);

               time += r;
               ac++;
               bc++;
           }
       }
       if(ac>=k&&bc>=k)
        System.out.println("\n"+time);
       else System.out.println(-1);


        br.close();
    }

}
