def main():
    (n, k,) = map(int, input().split(' '))
    tab = [list(map(int, input().split(' '))) for i in range(n)]
    tab.sort(key= lambda x: x[0])
    if sum([x[1] for x in tab]) < k or sum([x[2] for x in tab]) < k:
        return -1

    a_both = 0
    n_both = 0
    for x in tab:
        if x[1]==1 and x[2]==1:
            a_both += x[0]
            n_both +=1
            if n_both == k:
                return a_both

    n_alice = n_both
    n_bob = n_both

    for x in tab:
        if x[1]==1 and x[2]==1:
            continue
        if x[1] == 1 and n_alice < k:
            a_both += x[0]
            n_alice += 1
        if x[2] == 1 and n_bob < k:
            a_both += x[0]
            n_bob+=1

    return a_both


#for _ in range(int(input())):
print(main())
