n,k = [int(x) for x in input().split()]
# bl = []
# alice = []
at = []
# bob = []
bt = []
# common = []
ct = []
# none = []
# nt = []
# times = []
for i in range(n):
    ti,ai,bi = [int(x) for x in input().split()]
    if ai == 1 and bi == 1:
        # common.append(i)
        ct.append(ti)
    elif ai == 1:
        # alice.append(i)
        at.append(ti)
    elif bi == 1:
        # bob.append(i)
        bt.append(ti)
    else:
        # none.append(i)
        # nt.append(ti)
        continue
    # times.append(ti)
    # bl.append([ti,ai,bi]) #not needed
if len(ct)+len(at)<k or len(ct)+len(bt)<k:
    print(-1)
else:
    if len(ct)>=k:
        ct.sort()
        print(sum(ct[:k]))
    else:
        aleft = k - len(ct)
        bleft = k - len(ct)
        ans = sum(ct)
        at.sort()
        bt.sort()
        ans+=sum(at[:aleft])+sum(bt[:bleft])
        print(ans)