#include <bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
int main() {
  cin.sync_with_stdio(0);
  cin.tie(0);
  cin.exceptions(cin.failbit);
  long long int i, j, k, n, x, y, t, p, ans, z, cnt;
  t = 1;
  while (t--) {
    cin >> n >> k;
    vector<long long int> a, b, c;
    for (i = 0; i < (n); ++i) {
      cin >> x >> y >> z;
      if (y * z == 1)
        c.push_back(x);
      else {
        if (z == 1)
          b.push_back(x);
        else if (y == 1)
          a.push_back(x);
      }
    }
    sort(a.begin(), a.end());
    sort(b.begin(), b.end());
    sort(c.begin(), c.end());
    x = 2000;
    j = 1000000007 * x;
    a.push_back(j);
    b.push_back(j);
    c.push_back(j);
    long long int q = j;
    ans = 0, x = 0, y = 0, i = 0, j = 0, p = 0;
    while ((x < k || y < k) && ans < q) {
      if (x < k) {
        if (c[p] < a[i]) {
          ans += c[p];
          p++;
          x++;
          y++;
        } else {
          ans += a[i];
          i++;
          x++;
        }
      } else {
        if (c[p] < b[j]) {
          ans += c[p];
          p++;
          x++;
          y++;
        } else {
          ans += b[j];
          j++;
          y++;
        }
      }
    }
    if (ans >= q) ans = -1;
    cout << ans << endl;
  }
  return 0;
}
