#include <bits/stdc++.h>
using namespace std;

#define IOS ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ll long long
#define vll vector<ll>
#define vi vector<int>
#define pb push_back
#define fi first
#define se second
#define pii pair<int,int>
#define pll pair<ll,ll>
#define mii map<int,int>
#define mll map<ll,ll>
#define all(x) (x).begin(),(x).end()
#define S(x) (int)(x).size()
#define L(x) (int)(x).length()

#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<int , null_type , less<int> , rb_tree_tag , tree_order_statistics_node_update> ordered_set;

const int mod = 1e9+7;
const ll infl = 0x3f3f3f3f3f3f3f3fLL;
const int infi = 0x3f3f3f3f;

int t[200009],a[200009],b[200009],ind[200009];

void solve()
{
	int n,k,i;
	cin>>n>>k;
	for(i=0;i<n;i++) cin>>t[i]>>a[i]>>b[i];
	iota(ind,ind+n,0);
	sort(ind,ind+n,[](int A, int B){return t[A]<t[B];});
	int aa=0,bb=0;
	ll tot=0;
	for(i=0;i<n && aa<k;i++)
	{
		if(a[ind[i]]==0) continue;
		aa++;
		tot += t[ind[i]];
		bb += b[ind[i]];
	}
	for(i=0;i<n && bb<k;i++)
	{
		if(b[ind[i]]==0) continue;
		bb++;
		aa+=a[ind[i]];
		tot += t[ind[i]];
		//if(bb==k) break;
	}
	for(int j=i-1;j>=0;j--)
	{
		if(a[ind[j]]==0 || b[ind[j]]==1) continue;
		aa--;
		tot -= t[ind[j]];
		if(aa==k) break;
	}
	if(aa!=k || bb!=k)
	{
		cout<<-1<<'\n';
		return;
	}
	cout<<tot<<'\n';
}

int main()
{
	IOS
	int t_=1;
	//cin>>t;
	while(t_--)
	{
		solve();
	}
}
