#include<bits/stdc++.h>
using namespace std;
#define ll long long
map<ll , ll>m;
int main()
{
    ll n , k;
    cin >> n >> k;
    vector<ll>r1 , r2 , rb;
    for(ll i = 0 ; i < n ; i++)
    {
        ll x , b1 , b2;
        cin >> x >> b1 >> b2;
        if(b1 == 0 && b2 == 1)
        r2.push_back(x);
        if(b1 == 1 && b2 == 0)
        r1.push_back(x);
        if(b1 == 1 && b2 == 1)
        rb.push_back(x);
    }

    sort(r1.begin() , r1.end());
    sort(r2.begin() , r2.end());
    sort(rb.begin() , rb.end());
    ll n1 = r1.size();
    ll n2 = r2.size();
    ll nb = rb.size();
    ll p1[n1+1] = {0} , p2[n2+1] = {0} , pb[nb+1] = {0};


    for(ll i = 1 ; i <= n1 ; i++){
        p1[i] = p1[i-1]+r1[i-1];
    }

     for(ll i = 1 ; i <= n2 ; i++){
        p2[i] = p2[i-1]+r2[i-1];
    }

     for(ll i = 1 ; i <= nb ; i++){
        pb[i] = pb[i-1]+rb[i-1];
    }

    ll mini = 1e18;
    ll ans = -1;
    for(ll i = 0 ; i <= nb ; i++)
    {
        ll sum = (pb[i]);
        if((k-i > n1) || (k-i > n2))
        continue;

        sum += (p1[k-i]);
        sum += (p2[k-i]);

        if(mini > sum)
        {
            mini = sum;
            ans = mini;
        }
    }

    cout << ans ;




}
