/*   --------------------
    |       MAGIC        |
    |       ~KIRI~       |
     --------------------
*/
// #pragma comment(linker, "/stack:200000000")
// #pragma GCC optimize("Ofast")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <bits/stdc++.h>
#define inl(x) scanf("%lld",&x)
#define in(x) scanf("%d",&x)
#define ll long long
#define mp(x,y) make_pair(x,y)
#define mxx 100000000000000000
#define M 300005
#define pi acos(-1.)
#define Yesno(ok) if(ok)puts("YES");else puts("NO")
#define yesno(ok) if(ok)puts("Yes");else puts("No")

#define FASTIO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp> 
using namespace __gnu_pbds; 
  
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> 

int n,k;
vector<vector<int > > v;
bool ok[M];

int main()
{
    in(n);
    in(k);
    int x,y,z;
    for(int i=0;i<n;i++)
    {
        in(x);
        in(y);
        in(z);
        v.push_back({x,y,z});
    }
    ll s = 0 ;
    int a,b,till=-1;
    a=b=k;
    for(int i=0;i<n and (a or b);i++)
    {
        till = i;
        if(a)
            a-=v[i][1];
        if(b)
            b-=v[i][2];
    }
    if(a or b){ puts("-1");return 0;}
    a = b = k;
    int p,q;
    p = 1,q=2;
    if(v[till][1]==0)
        swap(p,q);
    for(int i=0;i<=till;i++)
    {
        if(v[i][p])
        {
            s+=v[i][0];
            if(v[i][q])
                a--,v[i][q]=0;
        }
    }
    for(int i=0;a and i<=till;i++)
    {
        if(v[i][q])
            s+=v[i][0];
    }
    cout << s << endl;
    return 0;
}