#include <bits/stdc++.h>

using namespace std;

int main(int argc, char* const argv[]){
	int nBooks, wRead, n1, n2, n3;
	int countA = 0, countB = 0, ans = 0;
	vector< pair < int, pair< int, int > > > pref;

	cin >> nBooks >> wRead;

	for(int i = 0; i < nBooks; i++){
		cin >> n1 >> n2 >> n3;

		pref.push_back(make_pair(n1, make_pair(n2, n3)));
	}

	sort(pref.begin(), pref.end(), [](auto &left, auto &right){
    	return left.first < right.first;
	});

	sort(pref.begin(), pref.end(), [](auto &left, auto &right){
    	return (left.second.first + left.second.second) > (right.second.first + right.second.second);
	});

	unsigned int i = 0;
	for(; i < pref.size(); i++){
		if(countA < wRead || countB < wRead){
			if(pref[i].second.first == 1 && pref[i].second.second == 1){
				countA++; countB++;

				if(pref[i].first != 0) ans += pref[i].first;
				else ans += 1;
			}
			else if(pref[i].second.first == 1){
				countA++;

				ans += pref[i].first;
			}
			else if(pref[i].second.second == 1){
				countB++;

				ans += pref[i].first;
			}

			if(i + 1 == pref.size() && countA < wRead && countB < wRead) ans = -1;
		}
		else break;
	}

	cout << ans << endl;

	return 0;
}