import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class E {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int k = scanner.nextInt();

        int[][] ar = new int[n][2];
        for(int i=0;i<n;i++) {
            ar[i][0] = scanner.nextInt();
            int a = scanner.nextInt();
            int b = scanner.nextInt();
            ar[i][1] = (a<<1) + b;
        }

        Arrays.sort(ar, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return (o1[0] == o2[0] ? o2[1] - o1[1] : o1[0] - o2[0]);
            }
        });

        int ak = 0, bk = 0, i = 0, res = 0;
        while(i<n && (ak<k || bk<k)) {
            if (ar[i][1] > 0) {
                res += ar[i][0];
                if ((ar[i][1] & 2) > 0) ak++;
                if ((ar[i][1] & 1) > 0) bk++;
            }
            i++;
        }

        if(ak < k || bk < k) System.out.println(-1);
        else {
            if (ak != bk) {
                int r, d = 0;
                if (ak > bk) r = 2;
                else r = 1;
                d = Math.abs(ak - bk);
                while (--i >= 0 && d > 0)
                    if (ar[i][1] == r) {
                        d--;
                        res -= ar[i][0];
                    }
            }
            System.out.println(res);
        }
    }
}
