arr = []
n, k = list(map(int, input().strip().split()))
for _ in range(n):
    arr.append(list(map(int, input().strip().split())))
a, b, c = 0, 0, 0
d, e, f = [], [], []
for n in range(n):
    if arr[n][1] == 1 and arr[n][2] == 0:
        a += 1
        d.append(arr[n][0])
    elif arr[n][1] == 0 and arr[n][2] == 1:
        c += 1
        f.append(arr[n][0])
    elif arr[n][1] == 1 and arr[n][2] == 1:
        b += 1
        e.append(arr[n][0])
d.sort()
e.sort()
f.sort()
if a + b < k or b + c < k:
    print(-1)
else:
    a, b = 0, 0
    ans = []
    x, y, z = [], [], []
    for i in e:
        if len(d) > 0 and len(f) > 0 and i > d[0] + f[0]:
            ans.append(d[0])
            d.pop(0)
            ans.append(f[0])
            f.pop(0)
            a += 1
        else:
            ans.append(i)
            b += 1
        if a + b == k:
            break
    if a + b < k:
        while a + b < k:
            ans.append(d[0])
            d.pop(0)
            ans.append(f[0])
            f.pop(0)
            a += 1
    print(sum(ans))