#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   D.py.py    
@Contact :   wangweixu@zuoyebang.com,liuyang05@zuoyebang.com,wangqian03@zuoyebang.com
@License :   (C)Copyright 2020-2022; All rights reserved.

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2020/10/23 4:30 下午   产品说的都队      1.0         None
'''


import sys
a=[]
b=[]
c=[]

n,m=sys.stdin.readline().strip().split(" ")

n=int(n)
m=int(m)

for i in range(n):
    x,y,z=sys.stdin.readline().strip().split(" ")
    if y=="1" and z=="1":
        a.append(int(x))
    if y=="1" and z=="0":
        b.append(int(x))
    if y=="0" and z=="1":
        c.append(int(x))

a.sort()
b.sort()
c.sort()
i,j,k=0,0,0
res=0
while m>0:
    if (i>=len(a)) and ((j>=len(b)) or (k>=len(c))):
        print -1
        exit(0)
    if i>=len(a):
        t1=-1
    else:
        t1=a[i]
    if j>=len(b):
        t2=-1
    else:
        t2=b[j]
    if k>=len(c):
        t3= -1
    else:
        t3=c[k]

    if (t1==-1):
        ss=t2+t3

        res+=ss
        j+=1
        k+=1
        m-=1

    else:
        if (t2 == -1) or (t3==-1):
            res+=t1
            i+=1
            m-=1
        else:

            ss = t2+t3

            if t1>ss:
                res+=ss
                m-=1
                j+=1
                k+=1
            else:
                res+=t1
                m-=1
                i+=1


print res

	 	     				  		   		 		    			