import sys

line = sys.stdin.readline().strip()
n,k = map(int, line.split(" "))
l = []
for i in range(0,n):
    line = sys.stdin.readline().strip()
    t,x,y = map(int, line.split(" "))
    l.append([t,x,y])

l.sort()

a = []
anum = 0
b = []
bnum = 0
sumt = 0
ans = -1

for i in range(0,n):
    t,x,y = l[i]
    if x == 0 and y == 0:
        continue
    if x == 1 and anum >= k and y == 0:
        continue
    if y == 1 and bnum >= k and x == 0:
        continue
    if x == 1:
        anum += 1
        if y == 0:
            a.append(t)
    if y == 1:
        bnum += 1
        if x == 0:
            b.append(t)
    sumt += t
    if x == 1 and y == 1:
        if anum > k and len(a) > 0:
            tt = a.pop()
            sumt -= tt
            anum -= 1
        if bnum > k and len(b) > 0:
            tt =  b.pop()
            sumt -= tt
            bnum -= 1
    if anum >= k and bnum >= k:
        if ans == -1 or ans > sumt:
            ans = sumt
        #if x == 1 and y == 1:
        #    break
    #print t,x,y,sumt,ans

print ans
  		 				  	 			 	 	 	 	 	 			