
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class EasyReadingBook {
    static class lib {
        int t, a, b;
        boolean flag;

        public lib(int t, int a, int b, boolean flag) {
            this.t = t;
            this.a = a;
            this.b = b;
            this.flag = flag;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String l = reader.readLine();
        String[] a = l.split(" ");
        int n = Integer.parseInt(a[0]);
        int k = Integer.parseInt(a[1]);
        List<lib> libList = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            l = reader.readLine();
            a = l.split(" ");
            int t = Integer.parseInt(a[0]);
            int A = Integer.parseInt(a[1]);
            int B = Integer.parseInt(a[2]);
            libList.add(new lib(t, A, B, false));
        }
        libList.sort(new Comparator<lib>() {
            @Override
            public int compare(lib lib, lib t1) {
                return lib.t - t1.t;
            }
        });
        long ans = 0;
        long A = 0, B = 0;
        for (int i = 0; i < n; i++) {
            if (A >= k || B >= k)
                break;
            if (libList.get(i).a == 1 && libList.get(i).b == 1) {
                ans += libList.get(i).t;
                A++;
                B++;
                libList.get(i).flag = true;
            }
        }
        if (A < k) {
            for (int i = 0; i < n; i++) {
                if (A >= k)
                    break;
                if (!libList.get(i).flag && libList.get(i).a == 1) {
                    ans += libList.get(i).t;
                    A++;
                    libList.get(i).flag = true;
                }
            }
        }

        if (B < k) {
            for (int i = 0; i < n; i++) {
                if (B >= k)
                    break;
                if (!libList.get(i).flag && libList.get(i).b == 1) {
                    ans += libList.get(i).t;
                    B++;
                    libList.get(i).flag = true;
                }
            }
        }
        if (A < k || B < k)
            System.out.println(-1);
        else
            System.out.println(ans);
    }
}
