#include<bits/stdc++.h> 
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp> 
#define mod 1000000009
#define mod2 998244353
#define int long long
#define endl "\n"
#define p_b push_back
#define m_p make_pair
#define fastIO ios_base::sync_with_stdio(false),cin.tie(NULL)
using namespace std;
using namespace __gnu_pbds;
template <class T> 
using _ost = tree<
		T, 
		null_type, 
		less_equal<T>, 
		rb_tree_tag, 
        tree_order_statistics_node_update>;

// char alphabet[26] = {'a','b','c','d','e','f','g','h','i',
//        'j','k','l','m','n','o','p','q','r','s','t','u','v',
//        'w','x','y','z'};

// const int mx = 5000005;


int32_t main() {
 	fastIO;
	int tc;
	// cin >> tc;
	tc = 1;
	while(tc--) {
		int n,k;
		cin >> n >> k;
		int t[n], a[n], b[n];
		vector<int> v1,v2,v3;
		int x=0,y=0;
		for(int i=0;i<n;i++) {
			cin >> t[i] >> a[i] >> b[i];
			if(a[i] && b[i]){
				v3.p_b(t[i]);
				x++;y++;
			}
			else if(a[i]) {
				v2.p_b(t[i]);
				x++;
			}
			else {
				v1.p_b(t[i]);
				y++;
			}	
		}
		if(x<k || y<k){
			cout << -1 << endl;
			return 0;
		}
		sort(v1.begin(),v1.end());reverse(v1.begin(),v1.end());
		sort(v2.begin(),v2.end());reverse(v2.begin(),v2.end());
		sort(v3.begin(),v3.end());reverse(v3.begin(),v3.end());
		x=0;y=0;
		int sm=0;
		while(x<k && y<k) {
			if(v1.size() && v2.size() && v3.size()) {
				if(v1.back()+v2.back() < v3.back()) {
					sm += v1.back()+v2.back();
					v1.pop_back();
					v2.pop_back();
				}
				else{
					sm += v3.back();
					v3.pop_back();
				}
				x++;y++;
			}
			else if(v3.size()) {
				sm += v3.back();
				v3.pop_back();
				x++;y++;
			}
			else break;
		} 
		while(x<k) {
			if(v3.size() && v1.size()) {
				if(v1.back() < v3.back()) {
					sm += v1.back();
					v1.pop_back();
					x++;
				}
				else {
					sm += v3.back();
					v3.pop_back();
					x++;y++;
				}
			}
			else if(v1.size()){
				sm += v1.back();
				v1.pop_back();
				x++;
			}
			else if(v3.size()) {
				sm += v3.back();
				v3.pop_back();
				x++;y++;
			}
			else break;
		}
		while(y<k) {
			if(v3.size() && v2.size()) {
				if(v2.back() < v3.back()) {
					sm += v2.back();
					v2.pop_back();
					y++;
				}
				else {
					sm += v3.back();
					v3.pop_back();
					x++;y++;
				}
			}
			else if(v2.size()){
				sm += v2.back();
				v2.pop_back();
				y++;
			}
			else if(v3.size()) {
				sm += v3.back();
				v3.pop_back();
				x++;y++;
			}
			else break;
		}		
		if(x>=k && y>=k) {
			cout << sm << endl;
		}
		else
			cout << -1 << endl;
	}
}