/*
Just Another Source code by -
Ambuj              
*/
#include<bits/stdc++.h>
using namespace std;
#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }

void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
	cerr << *it << " = " << a << endl;
	err(++it, args...);
}
#define ll long long
#define vi vector<int>
#define vl vector<ll>
#define vvi vector<vector<int>>
#define vvl vector<vector<ll>>
#define pii pair<int,int>
#define pll pair<ll,ll>
#define VP vector< pll >
#define MOD 1000000007
#define mp make_pair
#define pb push_back
#define all(v) (v).begin(),(v).end()
#define FF first
#define SS second
#define teji  ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define DI int n;cin>>n;
#define rep(i,a,b) for(ll i=a;i<b;i++)

int sum() { return 0; }

template<typename T, typename... Args>
auto sum(T a, Args... args) { return a + sum(args...); }
struct qwe
{
ll t,x,y;
};
bool desc(qwe a,qwe b)
{
	return a.t < b.t;
}
int gcd(int a,int b)
{
	if(a==0)return b;
	if(b==0)return a;
	return gcd(b,a%b);
}

int main(){
#ifndef ONLINE_JUDGE
freopen("/home/ambuj/.config/sublime-text-3/Packages/User/input.txt","r",stdin);
freopen ("/home/ambuj/.config/sublime-text-3/Packages/User/output.txt","w",stdout);
#endif
ll n,k;
cin>>n>>k;
qwe s[n+1];
stack<ll> alice,bob;
ll a=k,b=k;
ll ans=0;
//ll t[n+1],x[n+1],y[n+1];
ll cnt1=0,cnt2=0;
rep(i,0,n)
{
	
	cin>>s[i].t>>s[i].x>>s[i].y;
	if(s[i].x==1)cnt1++;
	if(s[i].y==1)cnt2++;
	//if(s[i].x==1&&s[i].y==1)ans++,a--,b--;
}
if(cnt1<k||cnt2<k){cout<<-1<<endl;
return 0;}
sort(s,s+n,desc);
rep(i,0,n)
{
	//if(alice.size()==a&&bob.size()==b)break;
	if(s[i].x==0&&s[i].y==0)continue;
      if(a==0&&b==0)break;
	if(s[i].x==1&&s[i].y==1){
		if(a!=0&&b!=0&&alice.size()==a&&bob.size()==b){
          if(s[i].t<alice.top()+bob.top())
          {
          	ans-=alice.top();
          	ans-=bob.top();
          	alice.pop();bob.pop();
          	a--;b--;
          	ans+=s[i].t;
          }
          
		}
          if(!alice.empty()&&alice.size()==a){ans-=alice.top();alice.pop();}
          if(!bob.empty()&&bob.size()==b){ans-=bob.top();bob.pop();}
          ans+=s[i].t;
          a--;b--;
          
	}else
	{
	if(s[i].x==1&&alice.size()<a){
		alice.push(s[i].t);ans+=s[i].t;
	}else
	if(s[i].y==1&&bob.size()<b)
	{
		bob.push(s[i].t);ans+=s[i].t;
	}
}


}
 cout<<ans<<endl;

return 0;
}