// while( !(succeed == try()) );

#include "bits/stdc++.h"
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp> 

using namespace __gnu_pbds; 
using namespace std;

// Alpha // Alpha // Alpha // Alpha // Alpha // Alpha // Alpha // Alpha // Alpha // Alpha


#define int long long int
#define loop(i,s,e) for(int i=s; i<e; i++)
#define endl '\n'
#define vii vector<int>
#define pii pair<int, int>
#define ff first
#define ss second
#define N 100001
#define pb push_back
#define INF LLONG_MAX
#define inf INT_MAX

void INP();

#define bug(...)        __f (#__VA_ARGS__, __VA_ARGS__)
#define rtn                                       if(0)return;
template <typename Arg1>
void __f (const char* name, Arg1&& arg1) { rtn cout << name << " : " << arg1 << endl; }
template <typename Arg1, typename... Args>
void __f (const char* names, Arg1&& arg1, Args&&... args)
{     rtn 
     const char* comma = strchr (names + 1, ',');
     cout.write (names, comma - names) << " : " << arg1 << " | "; __f (comma + 1, args...);
}

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; 


// Alpha // Alpha // Alpha // Alpha // Alpha // Alpha // Alpha // Alpha // Alpha // Alpha


void alpha()
{    
    int n, k;
    cin>>n>>k;

    vector<int> a, b, both;
    int cnt1=0, cnt2=0;

    loop(i,0,n)
    {
        int t, l1, l2;
        cin>>t>>l1>>l2;

        if(l1 and !l2)
        {
            a.pb(t);
            cnt1++;
        }
        else if(!l1 and l2)
        {
            b.pb(t);
            cnt2++;
        }
        else if(l1 and l2)
        {
            both.pb(t);
            cnt1++;
            cnt2++;
        }
    }

    if(cnt1 < k or cnt2 < k)
    {
        cout<<-1<<endl;
        return;
    }

    sort(a.begin(), a.end());
    sort(b.begin(), b.end());
    sort(both.begin(), both.end());

    loop(i,1,a.size()) a[i] += a[i-1];
    loop(i,1,b.size()) b[i] += b[i-1];
    loop(i,1,both.size()) both[i] += both[i-1];

    int ans = inf;
    loop(i,0,both.size())
    {
        int cnt = i+1;
        int t = both[i];
        if(cnt >= k)
        {
            ans = min(ans, t);
            break;
        } 
        
        t += (k-cnt-1 < a.size() ? a[k-cnt-1] : inf);
        t += (k-cnt-1 < b.size() ? b[k-cnt-1] : inf);

        ans = min(ans, t);
    }

    cout<<ans<<endl;
}

int32_t main(){

    ios_base:: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
    INP();
    int t=1;
    //cin>>t;
    
    while(t--) alpha();

    return 0;

}






















inline void INP()
{
      #ifndef ONLINE_JUDGE
          freopen("input.txt",  "r",  stdin);
          freopen("output.txt", "w", stdout);
      #endif
}
 
