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

public class Main {

    public static void main(String[] args) {
        Problems problems = new Problems();
        problems.solve();
    }
}

class Problems {

    Parser parser = new Parser();

    void solve() {
        Problem problem = new Problem();
        int t = 1;
        for (int i = 0; i < t; i++) {
            problem.solve(i);
        }
    }

    class Problem {
        void solve(int testCase) {
            int n = parser.parseInt();
            int k = parser.parseInt();

            List<Integer> ts = new ArrayList<>();
            List<Integer> as = new ArrayList<>();
            List<Integer> bs = new ArrayList<>();
            for(int i = 0; i < n; i++) {
                int t = parser.parseInt();
                int a = parser.parseInt();
                int b = parser.parseInt();

                if(a == 1 && b == 1) {
                    ts.add(t);
                }
                if (a == 1 && b == 0) {
                    as.add(t);
                }
                if (a == 0 && b == 1) {
                    bs.add(t);
                }
            }

            as.sort(null);
            bs.sort(null);

            int minLen = Math.min(as.size(), bs.size());
            for(int i = 0; i < minLen; i++) {
                ts.add(as.get(i) + bs.get(i));
            }

            if(ts.size() < k) {
                System.out.println(-1);
                return;
            }

            System.out.println(ts.stream()
                    .limit(k)
                    .reduce(0, Integer::sum));

        }
    }
}

class Parser {
    private final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    private final Iterator<String> stringIterator = br.lines().iterator();
    private final Deque<String> inputs = new ArrayDeque<>();

    void fill() {
        while (inputs.isEmpty()) {
            if (!stringIterator.hasNext()) throw new NoSuchElementException();
            inputs.addAll(Arrays.asList(stringIterator.next().split(" ")));
            while (!inputs.isEmpty() && inputs.getFirst().isEmpty()) {
                inputs.removeFirst();
            }
        }
    }

    Integer parseInt() {
        fill();
        if (!inputs.isEmpty()) {
            return Integer.parseInt(inputs.pollFirst());
        }
        throw new NoSuchElementException();
    }

    Long parseLong() {
        fill();
        if (!inputs.isEmpty()) {
            return Long.parseLong(inputs.pollFirst());
        }
        throw new NoSuchElementException();
    }

    Double parseDouble() {
        fill();
        if (!inputs.isEmpty()) {
            return Double.parseDouble(inputs.pollFirst());
        }
        throw new NoSuchElementException();
    }

    String parseString() {
        fill();
        return inputs.removeFirst();
    }
}