function sortFunc(x, y) {
   var likeBothX = x[1] && x[2];
   var likeBothY = y[1] && y[2];
   if (likeBothX) {
      if (likeBothY) {
         return x[0] - y[0];
      }
      return -1;
   }
   if (likeBothY) {
      return 1;
   }
   return x[0] - y[0];
}

function solve() {
   var nk = read().split(' ').map(Number);
   var n = nk[0];
   var k = nk[1];
   var ca = 0;
   var cb = 0;
   var arr = [];
   for (var i = 0; i < n; i++) {
      var tab = read().split(' ').map(Number);
      if (!tab[1] && !tab[2]) {
         continue;
      }
      arr.push(tab);
      ca += tab[1];
      cb += tab[2];
   }
   if (ca < k || cb < k) {
      write(-1);
      return;
   }
   n = arr.length;
   arr.sort(sortFunc);
   var ans = 0;
   ca = k;
   cb = k;
   for (var i = 0; i < n; i++) {
      if (arr[i][1]) {
         if (arr[i][2]) {
            ca--;
            cb--;
            if (ca >=0 || cb >= 0) {
               ans += arr[i][0];
            }
         } else {
            ca--;
            if (ca >= 0) {
               ans += arr[i][0];
            }
         }
      } else {
         if (arr[i][2]) {
            cb--;
            if (cb >= 0) {
               ans += arr[i][0];
            }
         }
      }
   }
   write(ans);
}

function init() {
   var T;
   T = 1;
   //T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}


var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');
   
   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }
    
   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });
    
      RL.on('line', (line) => {
         MEMORY.push(line);
      });
    
      RL.on('close', init);
   }
} else {
   init();
}
 
function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
