import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
# import time,random,resource

# sys.setrecursionlimit(10**6)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)
def IF(c, t, f): return t if c else f
def YES(c): return IF(c, "YES", "NO")
def Yes(c): return IF(c, "Yes", "No")


def main():
    t = 1

    rr = []
    for _ in range(t):
        n,k = LI()
        tab = [LI() for _ in range(n)]

        a0 = []
        a1 = []
        a2 = []
        for t,a,b in tab:
            if a and b:
                a0.append(t)
            elif a:
                a1.append(t)
            elif b:
                a2.append(t)

        if len(a0) + min(len(a1), len(a2)) < k:
            return -1

        a0.sort()
        a1.sort()
        a2.sort()
        a0.append(inf)
        a1.append(inf)
        a2.append(inf)
        i0 = 0
        ii = 0
        r = 0
        for _ in range(k):
            if a0[i0] < a1[ii] + a2[ii]:
                r += a0[i0]
                i0 += 1
            else:
                r += a1[ii] + a2[ii]
                ii += 1

        rr.append(r)

    return JA(rr, "\n")


print(main())


