#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long int i, j, n, m, k, t, x = 0, y, ans = 0, minn, x1 = 0, x2 = 0,
                                  y1 = 0, y2 = 0;
  vector<pair<long long, pair<long long, pair<long long, long long> > > > v, v1,
      v0;
  cin >> n >> m >> k;
  for (i = 0; i < n; i++) {
    cin >> t >> x >> y;
    if (x != 0 || y != 0)
      v.push_back(make_pair(t, make_pair(i + 1, make_pair(x, y))));
    else
      v0.push_back(make_pair(t, make_pair(i + 1, make_pair(x, y))));
    if (x == 1) x1++;
    if (y == 1) y1++;
  }
  if (x1 < k || y1 < k)
    cout << "-1";
  else {
    sort((v).begin(), (v).end());
    for (i = 0; i < v.size(); i++)
      cout << v[i].first << " " << v[i].second.first << " "
           << v[i].second.second.first << " " << v[i].second.second.second
           << "\n";
    i = 0;
    while ((x2 < k || y2 < k) && i < v.size()) {
      if (v[i].second.second.first == 1 && v[i].second.second.second == 0) {
        if (x2 < k && k - y2 < m - v1.size()) {
          v1.push_back(v[i]);
          x2++;
        } else
          v0.push_back(v[i]);
      } else if (v[i].second.second.first == 0 &&
                 v[i].second.second.second == 1) {
        if (y2 < k && k - x2 < m - v1.size()) {
          v1.push_back(v[i]);
          y2++;
        } else
          v0.push_back(v[i]);
      } else {
        v1.push_back(v[i]);
        x2++;
        y2++;
      }
      i++;
    }
    if (x2 < k || y2 < k) {
      cout << "-1";
      exit(0);
    }
    for (i = i; i < v.size(); i++) v0.push_back(v[i]);
    sort((v0).begin(), (v0).end());
    for (i = 0; i < m - v1.size(); i++) ans += v0[i].first;
    for (i = 0; i < v1.size(); i++) ans += v1[i].first;
    cout << ans << "\n";
    for (i = 0; i < v1.size(); i++) cout << v1[i].second.first << " ";
    for (i = 0; i < m - v1.size(); i++) cout << v0[i].second.first << " ";
  }
}
