#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#define int long long int
#define M 1000000007
#define pb push_back
#define pf push_front
#define ulli unsigned long long int
#define what_is(x) cerr << #x << " is " << x << endl;
#define F  first
#define S  second
#define endl '\n'
using namespace std;
using namespace __gnu_pbds;
const double pi = acos(-1.0);
const int INF = 1e19L;
const int LG = 20;
const int N = 1e5+9;
const int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1};
//bool ok(int x, int y) { return x >= 0 && y >= 0 && x < n && y < m; }
//newX = x + dx[i]; newY = y + dy[i];
typedef tree<int,null_type,less_equal<int>,rb_tree_tag,tree_order_statistics_node_update>ordered_set;
int power(int x,int y){if(x==0)return 0;int res=1;while(y>0){if(y%2)res=(res*x)%M;x=(x*x)%M;y=y/2;}return res;}
bool isvowel(char c){if(c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || c=='A' || c=='E' || c=='I' || c=='O' || c=='U')return true;return false;}
deque<int> a,b,c,d;
int n,k;

int32_t main()
{
	//cout.precision(15);
	//cout.setf(ios::fixed,ios::floatfield);
	ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	//freopen("input.txt","r",stdin);
	//freopen("output.txt","w",stdout);
	int T=1;
	//cin>>T;
	while(T--)
	{
		int i,t,x,y,z,ans=0,ca=0,cb=0;
		cin>>n>>k;
		for(i=0;i<n;i++)
		{
			cin>>t>>x>>y;
			if(x and y)
			c.pb(t);
			else if(x)
			a.pb(t);
			else if(y)
			b.pb(t);
		}
		if((c.size()+a.size()<k) and (c.size()+b.size()<k))
		{
			cout<<-1<<endl;
			continue;
		}
		sort(a.begin(),a.end());
		sort(b.begin(),b.end());
		sort(c.begin(),c.end());
		while(ca<k or cb<k)
		{
			if(a.empty() or b.empty())
			{
				ans+=c.front();
				c.pop_front();
			}
			else if(c.empty())
			{
				ans+=a.front();
				ans+=b.front();
				a.pop_front();
				b.pop_front();
			}
			else
			{
				x=a.front(),y=b.front(),z=c.front();
				if(z<=x+y)
				{
					ans+=z;
					c.pop_front();
				}
				else
				{
					ans+=a.front();
					ans+=b.front();
					a.pop_front();
					b.pop_front();
				}
			}
			ca++,cb++;
		}
		cout<<ans<<endl;
	}
}

