#include <bits/stdc++.h>
using namespace std;
int a[200010][3];
bool cmp(int x, int y) { return a[x][0] <= a[y][0]; }
bool cmp2(int x, int y) { return a[x][0] >= a[y][0]; }
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n, k;
  cin >> n >> k;
  vector<int> s1, s2, s3;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < 3; ++j) {
      cin >> a[i][j];
    }
    if (a[i][1] == 1 && a[i][2] == 1) {
      s3.push_back(i);
    } else if (a[i][1] == 1) {
      s1.push_back(i);
    } else if (a[i][2] == 1) {
      s2.push_back(i);
    }
  }
  sort(s1.begin(), s1.end(), cmp);
  sort(s2.begin(), s2.end(), cmp);
  sort(s3.begin(), s3.end(), cmp2);
  if (s1.size() + s3.size() < k || s2.size() + s3.size() < k) {
    cout << -1 << endl;
    return 0;
  }
  for (int i = k; i < s1.size();) s1.pop_back();
  for (int i = k; i < s2.size();) s2.pop_back();
  int ans = 0;
  int x = k - max(s1.size(), s2.size());
  while (x--) {
    ans += a[s3.back()][0];
    s3.pop_back();
    --k;
  }
  x = k - s1.size();
  while (x--) {
    ans += a[s3.back()][0];
    s3.pop_back();
    --k;
    s2.pop_back();
  }
  x = k - s2.size();
  while (x--) {
    ans += a[s3.back()][0];
    s3.pop_back();
    --k;
    s1.pop_back();
  }
  while (not s3.empty()) {
    if (not s1.empty() && not s2.empty() &&
        a[s3.back()][0] < a[s1.back()][0] + a[s2.back()][0]) {
      s1.pop_back();
      s2.pop_back();
    } else if (not s1.empty() && a[s3.back()][0] < a[s1.back()][0]) {
      s1.pop_back();
    } else if (not s2.empty() && a[s3.back()][0] < a[s2.back()][0]) {
      s2.pop_back();
    } else
      break;
    cout << ("s3.size()") << " = " << s3.size() << endl;
    ans += a[s3.back()][0];
    s3.pop_back();
  }
  for (int i = 0; i < s1.size(); ++i) {
    ans += a[s1[i]][0];
  }
  for (int i = 0; i < s2.size(); ++i) {
    ans += a[s2[i]][0];
  }
  cout << ans << endl;
  return 0;
}
