#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std; 
using namespace __gnu_pbds;
 
#define ll long long int
#define pb push_back
#define endl "\n"
#define F first
#define S second

#define mp map<ll,ll>
#define vc vector<ll>
#define pq priority_queue<pair<ll,ll>,vector<pair<ll,ll>>,greater<pair<ll,ll>>>
#define MAX  *max_element
#define MIN  *min_element
#define lcm(a,b) (a*b)/__gcd(a,b)
#define des_sort(v) sort(v.begin(),v.end(),greater<int>())
//max xor btw range of two numbers..
 
#define max_XOR(a,b) (1 << int(log2(a ^ b) + 1)) - 1
#define c_ones(number) __builtin_popcountll(number)
#define flip_bits(number) static_cast<unsigned>(~number)
 
#define all(X) X.begin(),X.end()
#define rep(i,n) for(ll i=0;i<n;i++)
#define loop(itr,n) for(itr=n.begin();itr!=n.end();itr++)
 
#define FLUSH fflush(stdout)
#define FAST ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define pb_ds tree<pair<int,int>, null_type,less<pair<int,int>>, rb_tree_tag,tree_order_statistics_node_update> 
#define mod 1000000007
#define INF 1e18
 
const double PI = acos(-1);
 
bool compare(pair<int,int>a , pair<int,int>b){
	return a.first==b.first ? a.second<b.second : a.first < b.first;
}
 
struct hash_pair{ 
    template <class T1, class T2> 
    size_t operator()(const pair<T1, T2>& p) const
    { 
        auto hash1 = hash<T1>{}(p.first); 
        auto hash2 = hash<T2>{}(p.second); 
        return hash1 ^ hash2; 
    } 
};
 
int main(){
	ll n,k;
	cin>>n>>k;
	ll num=k;
	vector<ll>a,b,c;
	ll x=0,y=0;
	ll p,q,r;
	rep(i,n){
		cin>>p>>q>>r;
		if(q==1)x++;
		if(r==1)y++;
		if(q==0&&r==1)b.pb(p);
		if(q==1&&r==0)c.pb(p);
		if(q&&r)a.pb(p);
	}
	if(x<k||y<k){
		cout<<-1<<endl;
		return 0;
	}
	sort(all(a));
	sort(all(b));
	sort(all(c));
	k=0;
	int i=0,j=0;
	x=0,y=0;
	ll ans=0;
	while(1){
		if(i<b.size()&&j<c.size()){
			cout<<i<<" "<<j<<endl;
			if(k<a.size()){
				if(b[i]+c[j]<a[k]){
					ans+=b[i]+c[j];
					i++;j++;
				}
				else{
					ans+=a[k];
					k++;
				}
				x++;y++;
				if(x+y==(2*num)){
					cout<<ans<<endl;
					return 0;
				}
			}
			else{
				ans+=b[i]+c[j];
				i++;j++;
				x++;y++;
				if(x+y==(2*num)){
					cout<<ans<<endl;
					return 0;
				}
			}
		}
		else break;
	}
	if(i==b.size()){
		int f;
		for(f=k;f<a.size();f++){
			ans+=a[f];
			x++;y++;
			if(x==k)break;
		}

		for(int g=j;g<c.size();g++){
			if(y>=k)break;
			if(f<a.size()){
				ans+min(a[f],c[g]);
				f++;
			}
			else{
				ans+=c[g];
			}
		}
		cout<<ans<<endl;
	}
	else if(j==c.size()){
		int f;
		for(f=k;f<a.size();f++){
			ans+=a[f];
			x++;y++;
			if(y==k)break;
		}
		for(int g=i;g<b.size();g++){
			if(x>=k)break;
			if(f<a.size()){
				ans+min(a[f],b[g]);
				f++;
			}
			else{
				ans+=b[g];
			}
		}
		cout<<ans<<endl;
	}
	else if(i==b.size()&&j==c.size()){
		for(int f=k;f<a.size();f++){
			ans+=a[f];
			x++;y++;
			if(x>=k&&y>=k)break;
		}
		cout<<ans<<endl;
	}
}