#include <bits/stdc++.h>
using namespace std;
struct s {
  int t;
  int a;
  int b;
};
bool compare(struct s a, struct s b) {
  if (a.t == b.t) {
    return !(b.a == 1 and b.b == 1);
  }
  return a.t < b.t;
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  int t = 1;
  while (t--) {
    int n, k;
    cin >> n >> k;
    struct s arr[n];
    for (int i = 0; i < n; i++) {
      cin >> arr[i].t >> arr[i].a >> arr[i].b;
    }
    sort(arr, arr + n, compare);
    deque<int> need, dont_need_a, dont_need_b;
    int index = 0, a = 0, b = 0;
    for (int i = 0; i < n; i++) {
      if (arr[i].a == 0 and arr[i].b == 0) {
        continue;
      }
      if (arr[i].a == 1) {
        a++;
      }
      if (arr[i].b == 1) {
        b++;
      }
      if (arr[i].a == 1 and arr[i].b == 1) {
        need.push_back(i);
      } else {
        if (arr[i].a == 1) {
          dont_need_a.push_back(i);
        } else {
          dont_need_b.push_back(i);
        }
      }
      if (a >= k and b >= k) {
        index = i + 1;
        break;
      }
    }
    int x, y;
    if (need.size() == k) {
      dont_need_b.clear();
      dont_need_a.clear();
    } else if (!need.empty()) {
      x = k - (int)need.size();
      if (dont_need_a.size() > x) {
        x = (int)dont_need_a.size() - x;
        while (x--) {
          dont_need_a.pop_back();
        }
      }
      x = k - (int)need.size();
      if (dont_need_b.size() > x) {
        x = (int)dont_need_b.size() - x;
        while (x--) {
          dont_need_a.pop_back();
        }
      }
    }
    for (int i = index; i < n; i++) {
      if (dont_need_a.empty() or dont_need_b.empty()) break;
      if (arr[i].a == 1 and arr[i].b == 1) {
        x = dont_need_b.back();
        y = dont_need_a.back();
        if (arr[x].t + arr[y].t > arr[i].t) {
          need.push_back(i);
          dont_need_b.pop_back();
          dont_need_a.pop_back();
        } else {
          break;
        }
      }
    }
    long long int ans = 0;
    for (int i : need) {
      ans += arr[i].t;
    }
    for (int i : dont_need_a) {
      ans += arr[i].t;
    }
    for (int i : dont_need_b) {
      ans += arr[i].t;
    }
    if (a >= k and b >= k) {
      cout << ans << "\n";
    } else {
      cout << "-1\n";
    }
  }
}
