n,k = map(int,input().split())
l = []
for _ in range(n):
    l.append(list(map(int,input().split())))
l1 = []
l2 = []
for i in l:
    if i[1] == 1:
        l1.append(i)
    elif i[2] == 1:
        l2.append(i)
l1.sort(key = lambda x:x[0])
l2.sort(key = lambda x:x[0])
i = 0
a = 0
b = 0
j = 0
s = 0
while i < len(l1) and a < k:
    s += l1[i][0]
    a += l1[i][1]
    b += l1[i][2]
    i += 1
i = 0
while i < len(l2) and b < k:
    s += l2[i][0]
    b += l2[i][2]
    i += 1
if a >= k and b >= k:
    print(s)
else:
    print(-1)