Easy and hard versions are actually different problems, so read statements of both problems completely and carefully.

Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster.

There are $n$ books in the family library. The $i$-th book is described by three integers: $t_i$ — the amount of time Alice and Bob need to spend to read it, $a_i$ (equals $1$ if Alice likes the $i$-th book and $0$ if not), and $b_i$ (equals $1$ if Bob likes the $i$-th book and $0$ if not).

So they need to choose some books from the given $n$ books in such a way that:

  Alice likes at least $k$ books from the chosen set and Bob likes at least $k$ books from the chosen set;  the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). 

The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of $t_i$ over all books that are in the chosen set.

Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set.


-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 2 \cdot 10^5$).

The next $n$ lines contain descriptions of books, one description per line: the $i$-th line contains three integers $t_i$, $a_i$ and $b_i$ ($1 \le t_i \le 10^4$, $0 \le a_i, b_i \le 1$), where:

  $t_i$ — the amount of time required for reading the $i$-th book;  $a_i$ equals $1$ if Alice likes the $i$-th book and $0$ otherwise;  $b_i$ equals $1$ if Bob likes the $i$-th book and $0$ otherwise. 


-----Output-----

If there is no solution, print only one integer -1. Otherwise print one integer $T$ — the minimum total reading time of the suitable set of books.


-----Examples-----
Input
8 4
7 1 1
2 1 1
4 0 1
8 1 1
1 0 1
1 1 1
1 0 1
3 0 0

Output
18

Input
5 2
6 0 0
9 0 0
1 0 1
2 1 1
5 1 0

Output
8

Input
5 3
3 0 0
2 1 0
3 1 0
5 0 1
3 0 1

Output
-1

Source: codeforces | Difficulty: MEDIUM_HARD
Tags: Sorting

Data structures

Greedy algorithms


Solutions:
(n, k) = map(int, input().split())
a = []
b = []
both = []
for _ in range(n):
	(x, y, z) = map(int, input().split())
	if y == 1 and z == 1:
		both.append(x)
	elif y == 1:
		a.append(x)
	elif z == 1:
		b.append(x)
a.sort()
b.sort()
for i in range(min(len(a), len(b))):
	both.append(a[i] + b[i])
both.sort()
if len(both) < k:
	print(-1)
else:
	print(sum(both[:k]))


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

class Books:

	def __init__(self, time, alice_like, bob_like):
		self.time = time
		self.alice_like = alice_like
		self.bob_like = bob_like

def solve():
	(n, k) = map(int, input().split())
	books = []
	for i in range(n):
		(t, a, b) = map(int, input().split())
		books.append(Books(t, a == 1, b == 1))
	books_everybody_like = []
	books_alice_like = []
	books_bob_like = []
	for b in books:
		if b.alice_like and b.bob_like:
			books_everybody_like.append(b)
		elif b.alice_like:
			books_alice_like.append(b)
		elif b.bob_like:
			books_bob_like.append(b)
	books_alice_like = sorted(books_alice_like, key=lambda x: x.time)
	books_bob_like = sorted(books_bob_like, key=lambda x: x.time)
	for (a, b) in zip(books_alice_like, books_bob_like):
		books_everybody_like.append(Books(a.time + b.time, True, True))
	if len(books_everybody_like) < k:
		print(-1)
		return
	books_everybody_like = sorted(books_everybody_like, key=lambda x: x.time)
	answer = 0
	for i in range(k):
		answer += books_everybody_like[i].time
	print(answer)
solve()


import atexit
import io
import sys
import math
from collections import defaultdict, Counter
(n, k) = map(int, input().split())
c1 = 0
c2 = 0
l1 = []
l2 = []
l = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	c1 += a
	c2 += b
	if a + b == 2:
		l.append([t, i])
		continue
	if a == 1:
		l1.append([t, i])
	if b == 1:
		l2.append([t, i])
if c1 < k or c2 < k:
	print(-1)
else:
	l1.sort(reverse=True)
	l2.sort(reverse=True)
	l.sort(reverse=True)
	time = 0
	while k:
		if len(l1) == 0 or len(l2) == 0 or (l and l1[-1][0] + l2[-1][0] > l[-1][0]):
			time += l.pop()[0]
		else:
			time += l1.pop()[0]
			time += l2.pop()[0]
		k -= 1
	print(time)


from heapq import *
import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def main():
	(n, k) = MI()
	at = []
	bt = []
	ca = cb = 0
	tab = LLI(n)
	tab.sort(key=lambda x: (x[0], -x[1] - x[2]))
	ans = 0
	mn = 10 ** 16
	for (t, a, b) in tab:
		if a and b:
			ans += t
			ca += 1
			cb += 1
			if ca > k:
				t = -heappop(at)
				ca -= 1
				ans -= t
			if cb > k:
				t = -heappop(bt)
				cb -= 1
				ans -= t
		elif a and ca < k:
			ans += t
			ca += 1
			heappush(at, -t)
		elif b and cb < k:
			ans += t
			cb += 1
			heappush(bt, -t)
		if ca == k and cb == k:
			mn = min(ans, mn)
			if not at and (not bt):
				break
	if ca == k and cb == k:
		print(mn)
	else:
		print(-1)
main()


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
from collections import defaultdict
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
(n, k) = map(int, input().split())
a = list()
b = list()
c = list()
c1 = 0
c2 = 0
for i in range(n):
	(a1, a2, a3) = map(int, input().split())
	if a2 == 1 and a3 == 1:
		c.append(a1)
		c1 += 1
		c2 += 1
	elif a2 == 1:
		a.append(a1)
		c1 += 1
	elif a3 == 1:
		b.append(a1)
		c2 += 1
if c2 < k or c1 < k:
	print(-1)
else:
	a.sort()
	b.sort()
	for i in range(min(len(a), len(b))):
		c.append(a[i] + b[i])
	c.sort()
	r = 0
	for i in range(k):
		r += c[i]
	print(r)


(n, k) = map(int, input().split())
a = []
b = []
ab = []
for i in ' ' * n:
	(t, x, y) = map(int, input().split())
	if x & y:
		ab += [t]
	elif x:
		a += [t]
	elif y:
		b += [t]
for (i, j) in zip(sorted(a), sorted(b)):
	ab += [i + j]
if len(ab) < k:
	print(-1)
else:
	print(sum(sorted(ab)[:k]))


(n, k) = map(int, input().split())
U = []
A = []
B = []
for i in range(n):
	(a, b, c) = map(int, input().split())
	if b == 1 and c == 1:
		U.append(a)
	elif b == 1 and c == 0:
		A.append(a)
	elif b == 0 and c == 1:
		B.append(a)
A.sort()
B.sort()
U.sort()
for i in range(1, len(U)):
	U[i] += U[i - 1]
for i in range(1, len(A)):
	A[i] += A[i - 1]
for i in range(1, len(B)):
	B[i] += B[i - 1]
f_ans = 10000000000.0
cnt = 0
ans = 0
for i in range(-1, len(U)):
	cnt = i + 1
	ans = 0
	if i >= 0:
		ans = U[i]
	if k - cnt == 0:
		f_ans = min(ans, f_ans)
		break
	if k - cnt > len(A) or k - cnt > len(B):
		continue
	ans += A[k - cnt - 1] + B[k - cnt - 1]
	cnt = k
	f_ans = min(f_ans, ans)
f_ans = min(ans, f_ans)
if k - cnt > 0:
	print('-1')
else:
	print(f_ans)


(n, k) = map(int, input().split())
(l, l1, l2) = ([], [], [])
for i in range(n):
	(a, b, c) = map(int, input().split())
	if b == 1 and c == 1:
		l.append(a)
	elif b == 1 and c == 0:
		l1.append(a)
	elif b == 0 and c == 1:
		l2.append(a)
l1.sort()
l2.sort()
for j in range(min(len(l1), len(l2))):
	l.append(l1[j] + l2[j])
l.sort()
if len(l) < k:
	print(-1)
else:
	print(sum(l[:k]))


(n, k) = map(int, input().split())
a = []
b = []
ab = []
for i in range(n):
	(t, a1, b1) = map(int, input().split())
	if a1 == 1 and b1 == 1:
		ab.append(t)
	elif a1 == 1 and b1 == 0:
		a.append(t)
	elif a1 == 0 and b1 == 1:
		b.append(t)
a.sort()
a_i = 0
b.sort()
ab.sort()
ab_i = 0
sum_t = 0
count = 0
while count < k:
	if (a_i == len(a) or a_i == len(b)) and ab_i < len(ab):
		sum_t += ab[ab_i]
		ab_i += 1
	elif ab_i == len(ab) and a_i < len(a) and (a_i < len(b)):
		sum_t += a[a_i] + b[a_i]
		a_i += 1
	elif ab_i < len(ab) and a_i < len(a) and (a_i < len(b)):
		if a[a_i] + b[a_i] < ab[ab_i]:
			sum_t += a[a_i] + b[a_i]
			a_i += 1
		else:
			sum_t += ab[ab_i]
			ab_i += 1
	else:
		sum_t = -1
		break
	count += 1
print(sum_t)


(n, k) = map(int, input().split())
alice = []
bob = []
both = []
counta = 0
countb = 0
for i in range(0, n):
	l1 = list(map(int, input().split()))
	if l1[1] == 1 and l1[2] == 1:
		counta += 1
		countb += 1
		both.append(l1)
	elif l1[1] == 1:
		counta += 1
		alice.append(l1)
	elif l1[2] == 1:
		countb += 1
		bob.append(l1)
if counta < k or countb < k:
	print(-1)
else:
	t = 0
	alice.sort()
	bob.sort()
	both.sort()
	a = 0
	b = 0
	for i in range(1, k + 1):
		if b > min(len(alice), len(bob)) - 1:
			for j in range(a, a + k - i + 1):
				t = t + both[j][0]
			break
		if a > len(both) - 1:
			for j in range(b, b + k - i + 1):
				t = t + alice[j][0] + bob[j][0]
			break
		if both[a][0] <= alice[b][0] + bob[b][0]:
			t = t + both[a][0]
			a = a + 1
		else:
			t = t + alice[b][0] + bob[b][0]
			b = b + 1
	print(t)


(n, k) = map(int, input().split())
aa = []
bb = []
oo = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1:
		if b == 1:
			oo.append(t)
		else:
			aa.append(t)
	elif b == 1:
		bb.append(t)
if len(aa) + len(oo) < k or len(oo) + len(bb) < k:
	print(-1)
else:
	aa.sort(reverse=True)
	bb.sort(reverse=True)
	oo.sort(reverse=True)
	ans = 0
	for i in range(k):
		if len(oo) == 0:
			ans += aa.pop()
			ans += bb.pop()
		elif len(aa) == 0 or len(bb) == 0:
			ans += oo.pop()
		elif oo[-1] < aa[-1] + bb[-1]:
			ans += oo.pop()
		else:
			ans += aa.pop()
			ans += bb.pop()
	print(ans)


from sys import stdin
ip = stdin.readline
(n, k) = map(int, ip().split())
alike = []
blike = []
both = []
for _ in range(n):
	(t, a, b) = map(int, ip().split())
	if a and b:
		both.append(t)
	elif a:
		alike.append(t)
	elif b:
		blike.append(t)
lb = k - len(both)
aln = len(alike)
bln = len(blike)
if aln < lb or bln < lb:
	print('-1')
else:
	alike.sort()
	blike.sort()
	both += [alike[i] + blike[i] for i in range(min(aln, bln))]
	both.sort()
	print(sum(both[:k]))


from sys import stdin
from collections import deque
mod = 10 ** 9 + 7
import sys
import random
from queue import PriorityQueue
from collections import Counter as cc
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt, factorial, gcd, log2, inf, ceil
import heapq
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
from itertools import permutations
from math import factorial as f

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p
import sys
(n, k) = map(int, input().split())
ha = k
la1 = []
la2 = []
la3 = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 0:
		la1.append(t)
	elif a == 0 and b == 1:
		la2.append(t)
	elif a == 1 and b == 1:
		la3.append(t)
la1.sort()
la2.sort()
la3.sort()
ans = 0
count1 = 0
count2 = 0
(i, j, k) = (0, 0, 0)
z = max(len(la1), len(la2), len(la3))
while True:
	if i >= z and j >= z and (k >= z):
		break
	if count1 >= ha and count2 >= ha:
		break
	(t1, t2, t3) = (10 ** 18, 10 ** 18, 10 ** 18)
	try:
		t1 = la1[i]
	except:
		pass
	try:
		t2 = la2[j]
	except:
		pass
	try:
		t3 = la3[k]
	except:
		pass
	if count1 >= ha and count2 >= ha:
		break
	elif count1 < ha and count2 < ha:
		if t1 + t2 <= t3:
			count1 += 1
			count2 += 1
			ans += t1 + t2
			i += 1
			j += 1
		else:
			count1 += 1
			count2 += 1
			ans += t3
			k += 1
	elif count1 < ha and count2 >= ha:
		if t1 <= t3:
			i += 1
			ans += t1
		else:
			k += 1
			ans += t3
	elif count2 < ha and count1 >= ha:
		if t2 <= t3:
			j += 1
			ans += t2
		else:
			k += 1
			ans += t3
if ans >= 10 ** 18:
	print(-1)
else:
	print(ans)


(n, k) = map(int, input().split())
l = []
for i in range(n):
	l.append(list(map(int, input().split())))
(x, y, z) = ([], [], [])
for i in range(n):
	if l[i][1] == 1 and l[i][2] == 1:
		x.append(l[i][0])
	elif l[i][1] == 1 and l[i][2] == 0:
		y.append(l[i][0])
	elif l[i][1] == 0 and l[i][2] == 1:
		z.append(l[i][0])
y.sort()
z.sort()
for i in range(min(len(y), len(z))):
	x.append(y[i] + z[i])
x.sort()
if len(x) < k:
	print(-1)
else:
	print(sum(x[:k]))


def p(x):
	return x[0]
(n, k) = map(int, input().split())
a = []
for i in range(n):
	a.append(list(map(int, input().split())))
a.sort(key=p)
(alice, bob, common) = ([], [], [])
(al, bo) = (0, 0)
flag = 1
for i in a:
	if i[1] and (not i[2]) and (al < k):
		alice.append(i[0])
		al += 1
	if i[2] and (not i[1]) and (bo < k):
		bob.append(i[0])
		bo += 1
	if i[1] and i[2]:
		if flag:
			common.append(i[0])
			al += 1
			bo += 1
			if al > k and alice:
				alice.pop()
				al -= 1
			if bo > k and bob:
				bob.pop()
				bo -= 1
		elif alice and bob:
			if alice[-1] + bob[-1] > i[0]:
				alice.pop()
				bob.pop()
				common.append(i[0])
			else:
				break
	if al >= k and bo >= k:
		flag = 0
if al >= k and bo >= k:
	print(sum(alice) + sum(bob) + sum(common))
else:
	print(-1)


from heapq import heappush, heappop
from sys import stdin, stdout

def reading_books(n, k, ta, tb, tab):
	res = 0
	for i in range(k):
		if len(tab) == 0 and (len(ta) == 0 or len(tb) == 0):
			return -1
		t1 = 100000
		t2 = 100000
		t3 = 100000
		if len(tab) > 0:
			t1 = tab[0]
		if len(ta) > 0:
			t2 = ta[0]
		if len(tb) > 0:
			t3 = tb[0]
		if t1 <= t2 + t3:
			res += heappop(tab)
		else:
			res += heappop(ta) + heappop(tb)
	return res
(n, k) = map(int, stdin.readline().split())
ta = []
tb = []
tab = []
for i in range(n):
	(t, a, b) = map(int, stdin.readline().split())
	if a == 1 and b == 1:
		heappush(tab, t)
	elif a == 1:
		heappush(ta, t)
	elif b == 1:
		heappush(tb, t)
res = reading_books(n, k, ta, tb, tab)
stdout.write(str(res) + '\n')


import sys
input = sys.stdin.readline
(n, minn) = map(int, input().split())
a = []
(ca, cb) = (0, 0)
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x == 1:
		ca += 1
	if y == 1:
		cb += 1
	a.append((t, x, y))
if ca < minn or cb < minn:
	print(-1)
	return
(ca, cb) = (0, 0)
alice = []
bob = []
both = []
for i in range(n):
	if a[i][1] == a[i][2] == 1:
		both.append(a[i][0])
	elif a[i][1] != a[i][2]:
		if a[i][1] == 1:
			alice.append(a[i][0])
		else:
			bob.append(a[i][0])
alice.sort()
bob.sort()
both.sort()
(i, j, k) = (0, 0, 0)
ans = 0
while ca < minn or cb < minn:
	if (i < len(alice) and j < len(bob) and (k < len(both))) and alice[i] + bob[j] <= both[k]:
		ans += alice[i] + bob[j]
		ca += 1
		cb += 1
		i += 1
		j += 1
	elif (i < len(alice) and j < len(bob) and (k < len(both))) and alice[i] + bob[j] >= both[k]:
		ans += both[k]
		ca += 1
		cb += 1
		k += 1
	else:
		break
if i == len(alice):
	while ca < minn:
		ans += both[k]
		k += 1
		ca += 1
		cb += 1
if j == len(bob):
	while cb < minn:
		ans += both[k]
		k += 1
		ca += 1
		cb += 1
if k == len(both):
	while ca < minn:
		ans += alice[i]
		i += 1
		ca += 1
	while cb < minn:
		ans += bob[j]
		j += 1
		cb += 1
print(ans)


(n, k1) = map(int, input().split())
(l_a, l_b, l_comb) = ([], [], [])
for _ in range(n):
	(ra, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		l_comb.append(ra)
	elif a == 1:
		l_a.append(ra)
	elif b == 1:
		l_b.append(ra)
if len(l_comb) + len(l_a) < k1 or len(l_comb) + len(l_b) < k1:
	print(-1)
else:
	l_comb.sort()
	l_a.sort()
	l_b.sort()
	ans = 0
	(i, j, k) = (0, 0, 0)
	for _ in range(k1):
		if i < len(l_comb) and j < len(l_a) and (k < len(l_b)) and (l_comb[i] < l_a[j] + l_b[k]):
			ans += l_comb[i]
			i += 1
		elif j < len(l_a) and k < len(l_b):
			ans += l_a[j] + l_b[k]
			j += 1
			k += 1
		else:
			ans += l_comb[i]
			i += 1
	print(ans)


def addition(lst, k):
	lst_alice = []
	lst_bob = []
	lst_both = []
	addition_lst = []
	lst.sort()
	for i in range(len(lst)):
		if lst[i][1] == 1 and lst[i][2] == 0:
			lst_alice.append(lst[i])
		elif lst[i][1] == 0 and lst[i][2] == 1:
			lst_bob.append(lst[i])
		elif lst[i][1] == 1 and lst[i][2] == 1:
			lst_both.append(lst[i])
	n = min(len(lst_alice), len(lst_bob))
	addition_lst = [[lst_alice[i][j] + lst_bob[i][j] for j in range(3)] for i in range(n)]
	lst_both.extend(addition_lst)
	lst_both.sort()
	if len(lst_both) < k:
		return -1
	ret = 0
	for i in range(k):
		ret += lst_both[i][0]
	return ret
(n, k) = map(int, input().split())
lst = []
for _ in range(n):
	lst.append(list(map(int, input().split())))
print(addition(lst, k))


class Book:

	def __init__(self, time, for_alice, for_bob):
		self.time = time
		self.for_alice = bool(for_alice)
		self.for_bob = bool(for_bob)
		self.status = ('A' if self.for_alice else '') + ('B' if self.for_bob else '')

def get(li, i):
	try:
		return li[i].time
	except IndexError:
		return 10 ** 10
(n, k) = map(int, input().split())
books = [Book(*map(int, input().split())) for _ in range(n)]
(alice_rest, bob_rest) = (k, k)
for_alice_books = list(filter(lambda x: x.status == 'A', books))
for_bob_books = list(filter(lambda x: x.status == 'B', books))
for_both_books = list(filter(lambda x: x.status == 'AB', books))
for_alice_books = sorted(for_alice_books, key=lambda x: x.time)
for_bob_books = sorted(for_bob_books, key=lambda x: x.time)
for_both_books = sorted(for_both_books, key=lambda x: x.time)
(for_alice_books_index, for_bob_books_index, for_both_books_index) = (0, 0, 0)
total = 0
while alice_rest > 0 or bob_rest > 0:
	alice_var = get(for_alice_books, for_alice_books_index)
	bob_var = get(for_bob_books, for_bob_books_index)
	both_var = get(for_both_books, for_both_books_index)
	if all((i == 10 ** 10 for i in [alice_var, bob_var, both_var])):
		total = -1
		break
	if alice_rest > 0 and bob_rest > 0:
		if alice_var + bob_var > both_var:
			for_both_books_index += 1
			total += both_var
		else:
			for_alice_books_index += 1
			for_bob_books_index += 1
			total += alice_var + bob_var
		alice_rest -= 1
		bob_rest -= 1
	elif alice_rest == 0:
		if bob_var > both_var:
			for_both_books_index += 1
			total += both_var
		else:
			for_bob_books_index += 1
			total += bob_var
		bob_rest -= 1
	else:
		if alice_var > both_var:
			for_both_books_index += 1
			total += both_var
		else:
			for_alice_books_index += 1
			total += alice_var
		alice_rest -= 1
print(total if total < 10 ** 10 else -1)


import sys
(n, k) = [int(e) for e in input().split(' ')]
books = list()
books_map = dict()
for i in range(n):
	(t, a, b) = [int(e) for e in input().split(' ')]
	books.append((t, a, b, i))
	books_map[i] = (t, a, b)
books = sorted(books, key=lambda x: x[0] * (1 if x[1] == 1 else 10000000.0))
alice_pay_time = 0
alice_liked_books = list()
for book in books:
	if len(alice_liked_books) >= k:
		break
	if book[1] == 1 and book[2] == 0:
		alice_pay_time += book[0]
		alice_liked_books.append(book[3])
books = sorted(books, key=lambda x: x[0] * (1 if x[2] == 1 else 10000000.0))
bob_pay_time = 0
bob_liked_books = list()
for book in books:
	if len(bob_liked_books) >= k:
		break
	if book[2] == 1 and book[1] == 0:
		bob_pay_time += book[0]
		bob_liked_books.append(book[3])
books = sorted(books, key=lambda x: x[0] * (1 if x[1] == 1 and x[2] == 1 else 10000000.0))
pay_time = alice_pay_time + bob_pay_time
alice_liked_book_count = len(alice_liked_books)
bob_liked_book_count = len(bob_liked_books)
for book in books:
	if book[1] == 1 and book[2] == 1:
		if alice_liked_book_count < k or bob_liked_book_count < k:
			pay_time += book[0]
			alice_liked_book_count += 1
			bob_liked_book_count += 1
			if alice_liked_book_count > k:
				pay_time -= books_map[alice_liked_books[-1]][0]
				alice_liked_books.pop()
				alice_liked_book_count = k
			if bob_liked_book_count > k:
				pay_time -= books_map[bob_liked_books[-1]][0]
				bob_liked_books.pop()
				bob_liked_book_count = k
		elif len(alice_liked_books) == 0 or len(bob_liked_books) == 0:
			break
		elif book[0] < books_map[alice_liked_books[-1]][0] + books_map[bob_liked_books[-1]][0]:
			pay_time -= books_map[alice_liked_books[-1]][0]
			pay_time -= books_map[bob_liked_books[-1]][0]
			pay_time += book[0]
			alice_liked_books.pop()
			bob_liked_books.pop()
if alice_liked_book_count >= k and bob_liked_book_count >= k:
	print(pay_time)
else:
	print(-1)


from sys import stdin
input = lambda : stdin.readline().strip()
from math import ceil, sqrt, factorial, gcd
from collections import deque
(n, k) = map(int, input().split())
a1 = []
b1 = []
x = set()
y = set()
com = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b != 1:
		a1.append(t)
	if b == 1 and a != 1:
		b1.append(t)
	if a == 1 and b == 1:
		com.append(t)
s = set()
count = 0
a1.sort(reverse=True)
b1.sort(reverse=True)
com.sort(reverse=True)
a = k
b = k
if len(a1) + len(com) < k or len(b1) + len(com) < k:
	print(-1)
	exit()
while a > 0 or b > 0:
	if a > 0 and b > 0:
		if len(com) > 0:
			if len(a1) > 0 and len(b1) > 0:
				if a1[-1] + b1[-1] < com[-1]:
					count += a1.pop() + b1.pop()
					a -= 1
					b -= 1
				else:
					count += com.pop()
					a -= 1
					b -= 1
			else:
				count += com.pop()
				a -= 1
				b -= 1
		else:
			count += a1.pop() + b1.pop()
			a -= 1
			b -= 1
	elif len(com) > 0:
		if a > 0:
			if len(a1) > 0 and a1[-1] < com[-1]:
				count += a1.pop()
				a -= 1
			else:
				count += com.pop()
				a -= 1
				b -= 1
		elif len(b1) > 0 and b1[-1] < com[-1]:
			count += a1.pop()
			b -= 1
		else:
			count += com.pop()
			a -= 1
			b -= 1
	elif a > 0:
		count += a1.pop()
		a -= 1
	else:
		count += b1.pop()
		b -= 1
print(count)


(n, k) = list(map(int, input().split()))
(both, ab, ba) = ([0], [0], [0])
for i in range(n):
	(t, a, b) = list(map(int, input().split()))
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1:
		ab.append(t)
	elif b == 1:
		ba.append(t)
(both, ab, ba) = (sorted(both), sorted(ab), sorted(ba))
for i in range(1, len(both)):
	both[i] = both[i] + both[i - 1]
for i in range(1, len(ab)):
	ab[i] = ab[i] + ab[i - 1]
for i in range(1, len(ba)):
	ba[i] = ba[i] + ba[i - 1]
mini = None
for i in range(min(k + 1, len(both))):
	rest = k - i
	if len(ab) - 1 < rest or len(ba) - 1 < rest:
		pass
	else:
		cur = both[i] + ab[rest] + ba[rest]
		mini = min(mini, cur) if mini is not None else cur
if mini is None:
	print('-1')
else:
	print(mini)


import sys

def get_ints():
	return map(int, sys.stdin.readline().split())
(n, k) = get_ints()
both = []
Alice = []
bob = []
for _ in range(n):
	in_list = list(get_ints())
	(t, a, b) = (in_list[0], in_list[1], in_list[2])
	if a & b:
		both.append(t)
	elif a:
		Alice.append(t)
	elif b:
		bob.append(t)
Alice.sort()
bob.sort()
l = min(len(Alice), len(bob))
for i in range(l):
	both.append(Alice[i] + bob[i])
if len(both) < k:
	print(-1)
else:
	both.sort()
	print(sum(both[:k]))


(n, k) = map(int, input().split())
lBoth = []
lAlice = []
lBob = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		lBoth.append(t)
	elif a == 1:
		lAlice.append(t)
	elif b == 1:
		lBob.append(t)
if len(lBoth) + min(len(lAlice), len(lBob)) < k:
	print(-1)
else:
	lBob.sort()
	lAlice.sort()
	lBoth.sort()
	numP = 0
	numB = 0
	kol = 0
	tm = 0
	while kol < k:
		if numP == len(lAlice) or numP == len(lBob):
			tm += sum(lBoth[numB:numB + k - kol])
			break
		if numB == len(lBoth):
			tm += sum(lBob[numP:numP + k - kol]) + sum(lAlice[numP:numP + k - kol])
			break
		if lBob[numP] + lAlice[numP] < lBoth[numB]:
			tm += lAlice[numP] + lBob[numP]
			numP += 1
			kol += 1
		else:
			tm += lBoth[numB]
			numB += 1
			kol += 1
	print(tm)


(n, m) = map(int, input().split())
first = []
second = []
common = []
array = []
for s in range(n):
	(a, b, c) = map(int, input().split())
	array.append([a, b, c])
(f, s, d) = (0, 0, 0)
for i in range(n):
	a = array[i][0]
	b = array[i][1]
	c = array[i][2]
	if b == 1 and c == 1:
		common.append(a)
		d += 1
	elif b == 1 and c == 0:
		first.append(a)
		f += 1
	elif b == 0 and c == 1:
		second.append(a)
		s += 1
mini = min(f, s)
first.sort()
second.sort()
for i in range(mini):
	common.append(first[i] + second[i])
common.sort()
add = 0
if m <= d + mini:
	for i in range(m):
		add += common[i]
	print(add)
else:
	print(-1)


(n, k) = list(map(int, input().split()))
x = []
y = []
z = []
for i in range(n):
	(t, a, b) = list(map(int, input().split()))
	if a == 1 and b == 1:
		z.append(t)
	elif a == 0 and b == 1:
		y.append(t)
	elif a == 1 and b == 0:
		x.append(t)
x1 = len(x)
y1 = len(y)
z1 = len(z)
if min(x1, y1) + z1 < k:
	print(-1)
else:
	x.sort()
	y.sort()
	s = min(x1, y1)
	i = 0
	while i < s:
		z.append(x[i] + y[i])
		i += 1
	z.sort()
	print(sum(z[:k]))


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')

def solve(n, k, t, a, b):
	if a.count(1) < k or b.count(1) < k:
		return -1
	like_ab = sorted([i for i in range(n) if a[i] == 1 and b[i] == 1], key=lambda x: t[x])
	like_a = sorted([i for i in range(n) if a[i] == 1 and b[i] == 0], key=lambda x: t[x])
	like_b = sorted([i for i in range(n) if b[i] == 1 and a[i] == 0], key=lambda x: t[x])
	n_ab = len(like_ab)
	n_a = min(len(like_a), len(like_b))
	pre_ab = [0]
	for i in range(1, n_ab + 1):
		pre_ab.append(pre_ab[i - 1] + t[like_ab[i - 1]])
	pre = [0]
	for i in range(1, n_a + 1):
		pre.append(pre[i - 1] + t[like_a[i - 1]] + t[like_b[i - 1]])
	ans = sum(t)
	for x in range(n_ab + 1):
		if n_a >= k - x >= 0:
			ans = min(ans, pre_ab[x] + pre[k - x])
	return ans

def main():
	(n, k) = ria()
	t = []
	a = []
	b = []
	for _ in range(n):
		(ti, ai, bi) = ria()
		t.append(ti)
		a.append(ai)
		b.append(bi)
	wi(solve(n, k, t, a, b))

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


from sys import stdin
from collections import defaultdict
(n, k) = list(map(int, stdin.readline().rstrip().split(' ')))
alice = []
bob = []
both = []
for _ in range(n):
	(ti, ai, bi) = list(map(int, stdin.readline().rstrip().split(' ')))
	if ai == 1 and bi == 1:
		both.append(ti)
	elif ai == 1:
		alice.append(ti)
	elif bi == 1:
		bob.append(ti)
if len(both) + len(alice) < k or len(both) + len(bob) < k:
	print(-1)
	raise SystemExit
ki = 0
alice.sort()
bob.sort()
both.sort()
takenBooks = []
takenBooksExtra = []
for ele in both:
	takenBooks.append(ele)
	ki += 1
	if ki >= k:
		break
newIdx = 0
if ki < k:
	for i in range(min(len(alice), len(bob))):
		takenBooksExtra.append(alice[i])
		takenBooksExtra.append(bob[i])
		ki += 1
		newIdx = i + 1
		if ki == k:
			break
for i in range(newIdx, min(len(alice), len(bob))):
	if len(takenBooks) == 0:
		break
	if alice[i] + bob[i] < takenBooks[-1]:
		takenBooks.pop()
		takenBooksExtra.append(alice[i])
		takenBooksExtra.append(bob[i])
	else:
		break
print(sum(takenBooks) + sum(takenBooksExtra))


import time, math, bisect, sys
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi = 3.141592653589793

def II():
	return int(stdin.readline())

def IO():
	return stdin.readline()

def IP():
	return map(int, stdin.readline().split())

def L():
	return list(map(int, stdin.readline().split()))

def P(x):
	return stdout.write(str(x))

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

def lcm(a, b):
	return a * b // gcd(a, b)

def gcd(a, b):
	if a == 0:
		return b
	elif b == 0:
		return a
	if a > b:
		return gcd(a % b, b)
	else:
		return gcd(a, b % a)

def sieve():
	li = [True] * 1000001
	(li[0], li[1]) = (False, False)
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	prime = []
	for i in range(1000001):
		if li[i] == True:
			prime.append(i)
	return prime

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count

def readTree(v, e):
	adj = [set() for i in range(v + 1)]
	for i in range(e):
		(u1, u2, w) = IP()
		adj[u1].add((u2, w))
		adj[u2].add((u1, w))
	return adj

def dfshelper(adj, i, visited):
	nodes = 1
	visited[i] = True
	for ele in adj[i]:
		if visited[ele] == False:
			nd = dfshelper(adj, ele, visited)
			nodes += nd
	return nodes

def dfs(adj, v):
	visited = [False] * (v + 1)
	li = []
	for i in range(v):
		if visited[i] == False:
			nodes = dfshelper(adj, i, visited)
			li.append(nodes)
	return li
mx = 10 ** 9 + 7

def solve():
	(n, k) = IP()
	(a, b, ab) = ([], [], [])
	(at, bt) = (0, 0)
	for i in range(n):
		t = L()
		if t[-2] == 1 and t[-1] == 1:
			ab.append(t[0])
		elif t[-2] == 1 and t[-1] == 0:
			a.append(t[0])
		elif t[-2] == 0 and t[-1] == 1:
			b.append(t[0])
		at += t[0]
		bt += t[0]
	(at, bt) = (0, 0)
	t = 0
	a.sort(reverse=True)
	b.sort(reverse=True)
	ab.sort(reverse=True)
	while (at < k or bt < k) and (ab or (a and b)):
		if ab and a and b:
			(x, y) = (ab[-1], a[-1] + b[-1])
			if x <= y:
				t += ab.pop()
			else:
				t = t + a.pop() + b.pop()
		elif ab:
			t += ab.pop()
		else:
			t = t + a.pop() + b.pop()
		at += 1
		bt += 1
	if at == k and bt == k:
		print(t)
		return
	else:
		print(-1)
		return
solve()


(n, k) = map(int, input().split())
both = []
a = []
b = []
for _ in range(n):
	(t, ai, bi) = map(int, input().split())
	if ai == 1 and bi == 1:
		both.append(t)
	elif ai == 1:
		a.append(t)
	elif bi == 1:
		b.append(t)
both.sort()
a.sort()
b.sort()
for l in [both, a, b]:
	if len(l) < k:
		l += [10 ** 10] * (k - len(l))
if len(a) > k:
	a = a[:k]
if len(b) > k:
	b = b[:k]
if len(both) > k:
	both = both[:k]
out = 0
for i in range(k):
	out += min(a[i] + b[i], both[-i - 1])
if out >= 10 ** 10:
	print(-1)
else:
	print(out)


from __future__ import print_function
import sys
import traceback
from bisect import bisect_left, bisect_right, insort
from itertools import chain, repeat, starmap
from math import log
from operator import add, eq, ne, gt, ge, lt, le, iadd
from textwrap import dedent
try:
	from collections.abc import Sequence, MutableSequence
except ImportError:
	from collections import Sequence, MutableSequence
from functools import wraps
from sys import hexversion
if hexversion < 50331648:
	from itertools import imap as map
	from itertools import izip as zip
	try:
		from thread import get_ident
	except ImportError:
		from dummy_thread import get_ident
else:
	from functools import reduce
	try:
		from _thread import get_ident
	except ImportError:
		from _dummy_thread import get_ident

def recursive_repr(fillvalue='...'):

	def decorating_function(user_function):
		repr_running = set()

		@wraps(user_function)
		def wrapper(self):
			key = (id(self), get_ident())
			if key in repr_running:
				return fillvalue
			repr_running.add(key)
			try:
				result = user_function(self)
			finally:
				repr_running.discard(key)
			return result
		return wrapper
	return decorating_function

class SortedList(MutableSequence):
	DEFAULT_LOAD_FACTOR = 1000

	def __init__(self, iterable=None, key=None):
		assert key is None
		self._len = 0
		self._load = self.DEFAULT_LOAD_FACTOR
		self._lists = []
		self._maxes = []
		self._index = []
		self._offset = 0
		if iterable is not None:
			self._update(iterable)

	def __new__(cls, iterable=None, key=None):
		if key is None:
			return object.__new__(cls)
		elif cls is SortedList:
			return object.__new__(SortedKeyList)
		else:
			raise TypeError('inherit SortedKeyList for key argument')

	@property
	def key(self):
		return None

	def _reset(self, load):
		values = reduce(iadd, self._lists, [])
		self._clear()
		self._load = load
		self._update(values)

	def clear(self):
		self._len = 0
		del self._lists[:]
		del self._maxes[:]
		del self._index[:]
		self._offset = 0
	_clear = clear

	def add(self, value):
		_lists = self._lists
		_maxes = self._maxes
		if _maxes:
			pos = bisect_right(_maxes, value)
			if pos == len(_maxes):
				pos -= 1
				_lists[pos].append(value)
				_maxes[pos] = value
			else:
				insort(_lists[pos], value)
			self._expand(pos)
		else:
			_lists.append([value])
			_maxes.append(value)
		self._len += 1

	def _expand(self, pos):
		_load = self._load
		_lists = self._lists
		_index = self._index
		if len(_lists[pos]) > _load << 1:
			_maxes = self._maxes
			_lists_pos = _lists[pos]
			half = _lists_pos[_load:]
			del _lists_pos[_load:]
			_maxes[pos] = _lists_pos[-1]
			_lists.insert(pos + 1, half)
			_maxes.insert(pos + 1, half[-1])
			del _index[:]
		elif _index:
			child = self._offset + pos
			while child:
				_index[child] += 1
				child = child - 1 >> 1
			_index[0] += 1

	def update(self, iterable):
		_lists = self._lists
		_maxes = self._maxes
		values = sorted(iterable)
		if _maxes:
			if len(values) * 4 >= self._len:
				values.extend(chain.from_iterable(_lists))
				values.sort()
				self._clear()
			else:
				_add = self.add
				for val in values:
					_add(val)
				return
		_load = self._load
		_lists.extend((values[pos:pos + _load] for pos in range(0, len(values), _load)))
		_maxes.extend((sublist[-1] for sublist in _lists))
		self._len = len(values)
		del self._index[:]
	_update = update

	def __contains__(self, value):
		_maxes = self._maxes
		if not _maxes:
			return False
		pos = bisect_left(_maxes, value)
		if pos == len(_maxes):
			return False
		_lists = self._lists
		idx = bisect_left(_lists[pos], value)
		return _lists[pos][idx] == value

	def discard(self, value):
		_maxes = self._maxes
		if not _maxes:
			return
		pos = bisect_left(_maxes, value)
		if pos == len(_maxes):
			return
		_lists = self._lists
		idx = bisect_left(_lists[pos], value)
		if _lists[pos][idx] == value:
			self._delete(pos, idx)

	def remove(self, value):
		_maxes = self._maxes
		if not _maxes:
			raise ValueError('{0!r} not in list'.format(value))
		pos = bisect_left(_maxes, value)
		if pos == len(_maxes):
			raise ValueError('{0!r} not in list'.format(value))
		_lists = self._lists
		idx = bisect_left(_lists[pos], value)
		if _lists[pos][idx] == value:
			self._delete(pos, idx)
		else:
			raise ValueError('{0!r} not in list'.format(value))

	def _delete(self, pos, idx):
		_lists = self._lists
		_maxes = self._maxes
		_index = self._index
		_lists_pos = _lists[pos]
		del _lists_pos[idx]
		self._len -= 1
		len_lists_pos = len(_lists_pos)
		if len_lists_pos > self._load >> 1:
			_maxes[pos] = _lists_pos[-1]
			if _index:
				child = self._offset + pos
				while child > 0:
					_index[child] -= 1
					child = child - 1 >> 1
				_index[0] -= 1
		elif len(_lists) > 1:
			if not pos:
				pos += 1
			prev = pos - 1
			_lists[prev].extend(_lists[pos])
			_maxes[prev] = _lists[prev][-1]
			del _lists[pos]
			del _maxes[pos]
			del _index[:]
			self._expand(prev)
		elif len_lists_pos:
			_maxes[pos] = _lists_pos[-1]
		else:
			del _lists[pos]
			del _maxes[pos]
			del _index[:]

	def _loc(self, pos, idx):
		if not pos:
			return idx
		_index = self._index
		if not _index:
			self._build_index()
		total = 0
		pos += self._offset
		while pos:
			if not pos & 1:
				total += _index[pos - 1]
			pos = pos - 1 >> 1
		return total + idx

	def _pos(self, idx):
		if idx < 0:
			last_len = len(self._lists[-1])
			if -idx <= last_len:
				return (len(self._lists) - 1, last_len + idx)
			idx += self._len
			if idx < 0:
				raise IndexError('list index out of range')
		elif idx >= self._len:
			raise IndexError('list index out of range')
		if idx < len(self._lists[0]):
			return (0, idx)
		_index = self._index
		if not _index:
			self._build_index()
		pos = 0
		child = 1
		len_index = len(_index)
		while child < len_index:
			index_child = _index[child]
			if idx < index_child:
				pos = child
			else:
				idx -= index_child
				pos = child + 1
			child = (pos << 1) + 1
		return (pos - self._offset, idx)

	def _build_index(self):
		row0 = list(map(len, self._lists))
		if len(row0) == 1:
			self._index[:] = row0
			self._offset = 0
			return
		head = iter(row0)
		tail = iter(head)
		row1 = list(starmap(add, zip(head, tail)))
		if len(row0) & 1:
			row1.append(row0[-1])
		if len(row1) == 1:
			self._index[:] = row1 + row0
			self._offset = 1
			return
		size = 2 ** (int(log(len(row1) - 1, 2)) + 1)
		row1.extend(repeat(0, size - len(row1)))
		tree = [row0, row1]
		while len(tree[-1]) > 1:
			head = iter(tree[-1])
			tail = iter(head)
			row = list(starmap(add, zip(head, tail)))
			tree.append(row)
		reduce(iadd, reversed(tree), self._index)
		self._offset = size * 2 - 1

	def __delitem__(self, index):
		if isinstance(index, slice):
			(start, stop, step) = index.indices(self._len)
			if step == 1 and start < stop:
				if start == 0 and stop == self._len:
					return self._clear()
				elif self._len <= 8 * (stop - start):
					values = self._getitem(slice(None, start))
					if stop < self._len:
						values += self._getitem(slice(stop, None))
					self._clear()
					return self._update(values)
			indices = range(start, stop, step)
			if step > 0:
				indices = reversed(indices)
			(_pos, _delete) = (self._pos, self._delete)
			for index in indices:
				(pos, idx) = _pos(index)
				_delete(pos, idx)
		else:
			(pos, idx) = self._pos(index)
			self._delete(pos, idx)

	def __getitem__(self, index):
		_lists = self._lists
		if isinstance(index, slice):
			(start, stop, step) = index.indices(self._len)
			if step == 1 and start < stop:
				if start == 0 and stop == self._len:
					return reduce(iadd, self._lists, [])
				(start_pos, start_idx) = self._pos(start)
				start_list = _lists[start_pos]
				stop_idx = start_idx + stop - start
				if len(start_list) >= stop_idx:
					return start_list[start_idx:stop_idx]
				if stop == self._len:
					stop_pos = len(_lists) - 1
					stop_idx = len(_lists[stop_pos])
				else:
					(stop_pos, stop_idx) = self._pos(stop)
				prefix = _lists[start_pos][start_idx:]
				middle = _lists[start_pos + 1:stop_pos]
				result = reduce(iadd, middle, prefix)
				result += _lists[stop_pos][:stop_idx]
				return result
			if step == -1 and start > stop:
				result = self._getitem(slice(stop + 1, start + 1))
				result.reverse()
				return result
			indices = range(start, stop, step)
			return list((self._getitem(index) for index in indices))
		else:
			if self._len:
				if index == 0:
					return _lists[0][0]
				elif index == -1:
					return _lists[-1][-1]
			else:
				raise IndexError('list index out of range')
			if 0 <= index < len(_lists[0]):
				return _lists[0][index]
			len_last = len(_lists[-1])
			if -len_last < index < 0:
				return _lists[-1][len_last + index]
			(pos, idx) = self._pos(index)
			return _lists[pos][idx]
	_getitem = __getitem__

	def __setitem__(self, index, value):
		message = 'use ``del sl[index]`` and ``sl.add(value)`` instead'
		raise NotImplementedError(message)

	def __iter__(self):
		return chain.from_iterable(self._lists)

	def __reversed__(self):
		return chain.from_iterable(map(reversed, reversed(self._lists)))

	def reverse(self):
		raise NotImplementedError('use ``reversed(sl)`` instead')

	def islice(self, start=None, stop=None, reverse=False):
		_len = self._len
		if not _len:
			return iter(())
		(start, stop, _) = slice(start, stop).indices(self._len)
		if start >= stop:
			return iter(())
		_pos = self._pos
		(min_pos, min_idx) = _pos(start)
		if stop == _len:
			max_pos = len(self._lists) - 1
			max_idx = len(self._lists[-1])
		else:
			(max_pos, max_idx) = _pos(stop)
		return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)

	def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):
		_lists = self._lists
		if min_pos > max_pos:
			return iter(())
		if min_pos == max_pos:
			if reverse:
				indices = reversed(range(min_idx, max_idx))
				return map(_lists[min_pos].__getitem__, indices)
			indices = range(min_idx, max_idx)
			return map(_lists[min_pos].__getitem__, indices)
		next_pos = min_pos + 1
		if next_pos == max_pos:
			if reverse:
				min_indices = range(min_idx, len(_lists[min_pos]))
				max_indices = range(max_idx)
				return chain(map(_lists[max_pos].__getitem__, reversed(max_indices)), map(_lists[min_pos].__getitem__, reversed(min_indices)))
			min_indices = range(min_idx, len(_lists[min_pos]))
			max_indices = range(max_idx)
			return chain(map(_lists[min_pos].__getitem__, min_indices), map(_lists[max_pos].__getitem__, max_indices))
		if reverse:
			min_indices = range(min_idx, len(_lists[min_pos]))
			sublist_indices = range(next_pos, max_pos)
			sublists = map(_lists.__getitem__, reversed(sublist_indices))
			max_indices = range(max_idx)
			return chain(map(_lists[max_pos].__getitem__, reversed(max_indices)), chain.from_iterable(map(reversed, sublists)), map(_lists[min_pos].__getitem__, reversed(min_indices)))
		min_indices = range(min_idx, len(_lists[min_pos]))
		sublist_indices = range(next_pos, max_pos)
		sublists = map(_lists.__getitem__, sublist_indices)
		max_indices = range(max_idx)
		return chain(map(_lists[min_pos].__getitem__, min_indices), chain.from_iterable(sublists), map(_lists[max_pos].__getitem__, max_indices))

	def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False):
		_maxes = self._maxes
		if not _maxes:
			return iter(())
		_lists = self._lists
		if minimum is None:
			min_pos = 0
			min_idx = 0
		elif inclusive[0]:
			min_pos = bisect_left(_maxes, minimum)
			if min_pos == len(_maxes):
				return iter(())
			min_idx = bisect_left(_lists[min_pos], minimum)
		else:
			min_pos = bisect_right(_maxes, minimum)
			if min_pos == len(_maxes):
				return iter(())
			min_idx = bisect_right(_lists[min_pos], minimum)
		if maximum is None:
			max_pos = len(_maxes) - 1
			max_idx = len(_lists[max_pos])
		elif inclusive[1]:
			max_pos = bisect_right(_maxes, maximum)
			if max_pos == len(_maxes):
				max_pos -= 1
				max_idx = len(_lists[max_pos])
			else:
				max_idx = bisect_right(_lists[max_pos], maximum)
		else:
			max_pos = bisect_left(_maxes, maximum)
			if max_pos == len(_maxes):
				max_pos -= 1
				max_idx = len(_lists[max_pos])
			else:
				max_idx = bisect_left(_lists[max_pos], maximum)
		return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)

	def __len__(self):
		return self._len

	def bisect_left(self, value):
		_maxes = self._maxes
		if not _maxes:
			return 0
		pos = bisect_left(_maxes, value)
		if pos == len(_maxes):
			return self._len
		idx = bisect_left(self._lists[pos], value)
		return self._loc(pos, idx)

	def bisect_right(self, value):
		_maxes = self._maxes
		if not _maxes:
			return 0
		pos = bisect_right(_maxes, value)
		if pos == len(_maxes):
			return self._len
		idx = bisect_right(self._lists[pos], value)
		return self._loc(pos, idx)
	bisect = bisect_right
	_bisect_right = bisect_right

	def count(self, value):
		_maxes = self._maxes
		if not _maxes:
			return 0
		pos_left = bisect_left(_maxes, value)
		if pos_left == len(_maxes):
			return 0
		_lists = self._lists
		idx_left = bisect_left(_lists[pos_left], value)
		pos_right = bisect_right(_maxes, value)
		if pos_right == len(_maxes):
			return self._len - self._loc(pos_left, idx_left)
		idx_right = bisect_right(_lists[pos_right], value)
		if pos_left == pos_right:
			return idx_right - idx_left
		right = self._loc(pos_right, idx_right)
		left = self._loc(pos_left, idx_left)
		return right - left

	def copy(self):
		return self.__class__(self)
	__copy__ = copy

	def append(self, value):
		raise NotImplementedError('use ``sl.add(value)`` instead')

	def extend(self, values):
		raise NotImplementedError('use ``sl.update(values)`` instead')

	def insert(self, index, value):
		raise NotImplementedError('use ``sl.add(value)`` instead')

	def pop(self, index=-1):
		if not self._len:
			raise IndexError('pop index out of range')
		_lists = self._lists
		if index == 0:
			val = _lists[0][0]
			self._delete(0, 0)
			return val
		if index == -1:
			pos = len(_lists) - 1
			loc = len(_lists[pos]) - 1
			val = _lists[pos][loc]
			self._delete(pos, loc)
			return val
		if 0 <= index < len(_lists[0]):
			val = _lists[0][index]
			self._delete(0, index)
			return val
		len_last = len(_lists[-1])
		if -len_last < index < 0:
			pos = len(_lists) - 1
			loc = len_last + index
			val = _lists[pos][loc]
			self._delete(pos, loc)
			return val
		(pos, idx) = self._pos(index)
		val = _lists[pos][idx]
		self._delete(pos, idx)
		return val

	def index(self, value, start=None, stop=None):
		_len = self._len
		if not _len:
			raise ValueError('{0!r} is not in list'.format(value))
		if start is None:
			start = 0
		if start < 0:
			start += _len
		if start < 0:
			start = 0
		if stop is None:
			stop = _len
		if stop < 0:
			stop += _len
		if stop > _len:
			stop = _len
		if stop <= start:
			raise ValueError('{0!r} is not in list'.format(value))
		_maxes = self._maxes
		pos_left = bisect_left(_maxes, value)
		if pos_left == len(_maxes):
			raise ValueError('{0!r} is not in list'.format(value))
		_lists = self._lists
		idx_left = bisect_left(_lists[pos_left], value)
		if _lists[pos_left][idx_left] != value:
			raise ValueError('{0!r} is not in list'.format(value))
		stop -= 1
		left = self._loc(pos_left, idx_left)
		if start <= left:
			if left <= stop:
				return left
		else:
			right = self._bisect_right(value) - 1
			if start <= right:
				return start
		raise ValueError('{0!r} is not in list'.format(value))

	def __add__(self, other):
		values = reduce(iadd, self._lists, [])
		values.extend(other)
		return self.__class__(values)
	__radd__ = __add__

	def __iadd__(self, other):
		self._update(other)
		return self

	def __mul__(self, num):
		values = reduce(iadd, self._lists, []) * num
		return self.__class__(values)
	__rmul__ = __mul__

	def __imul__(self, num):
		values = reduce(iadd, self._lists, []) * num
		self._clear()
		self._update(values)
		return self

	def __make_cmp(seq_op, symbol, doc):

		def comparer(self, other):
			if not isinstance(other, Sequence):
				return NotImplemented
			self_len = self._len
			len_other = len(other)
			if self_len != len_other:
				if seq_op is eq:
					return False
				if seq_op is ne:
					return True
			for (alpha, beta) in zip(self, other):
				if alpha != beta:
					return seq_op(alpha, beta)
			return seq_op(self_len, len_other)
		seq_op_name = seq_op.__name__
		comparer.__name__ = '__{0}__'.format(seq_op_name)
		doc_str = 'Return true if and only if sorted list is {0} `other`.\n        ``sl.__{1}__(other)`` <==> ``sl {2} other``\n        Comparisons use lexicographical order as with sequences.\n        Runtime complexity: `O(n)`\n        :param other: `other` sequence\n        :return: true if sorted list is {0} `other`\n        '
		comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))
		return comparer
	__eq__ = __make_cmp(eq, '==', 'equal to')
	__ne__ = __make_cmp(ne, '!=', 'not equal to')
	__lt__ = __make_cmp(lt, '<', 'less than')
	__gt__ = __make_cmp(gt, '>', 'greater than')
	__le__ = __make_cmp(le, '<=', 'less than or equal to')
	__ge__ = __make_cmp(ge, '>=', 'greater than or equal to')
	__make_cmp = staticmethod(__make_cmp)

	def __reduce__(self):
		values = reduce(iadd, self._lists, [])
		return (type(self), (values,))

	@recursive_repr()
	def __repr__(self):
		return '{0}({1!r})'.format(type(self).__name__, list(self))

	def _check(self):
		try:
			assert self._load >= 4
			assert len(self._maxes) == len(self._lists)
			assert self._len == sum((len(sublist) for sublist in self._lists))
			for sublist in self._lists:
				for pos in range(1, len(sublist)):
					assert sublist[pos - 1] <= sublist[pos]
			for pos in range(1, len(self._lists)):
				assert self._lists[pos - 1][-1] <= self._lists[pos][0]
			for pos in range(len(self._maxes)):
				assert self._maxes[pos] == self._lists[pos][-1]
			double = self._load << 1
			assert all((len(sublist) <= double for sublist in self._lists))
			half = self._load >> 1
			for pos in range(0, len(self._lists) - 1):
				assert len(self._lists[pos]) >= half
			if self._index:
				assert self._len == self._index[0]
				assert len(self._index) == self._offset + len(self._lists)
				for pos in range(len(self._lists)):
					leaf = self._index[self._offset + pos]
					assert leaf == len(self._lists[pos])
				for pos in range(self._offset):
					child = (pos << 1) + 1
					if child >= len(self._index):
						assert self._index[pos] == 0
					elif child + 1 == len(self._index):
						assert self._index[pos] == self._index[child]
					else:
						child_sum = self._index[child] + self._index[child + 1]
						assert child_sum == self._index[pos]
		except:
			traceback.print_exc(file=sys.stdout)
			print('len', self._len)
			print('load', self._load)
			print('offset', self._offset)
			print('len_index', len(self._index))
			print('index', self._index)
			print('len_maxes', len(self._maxes))
			print('maxes', self._maxes)
			print('len_lists', len(self._lists))
			print('lists', self._lists)
			raise

def identity(value):
	return value

class SortedKeyList(SortedList):

	def __init__(self, iterable=None, key=identity):
		self._key = key
		self._len = 0
		self._load = self.DEFAULT_LOAD_FACTOR
		self._lists = []
		self._keys = []
		self._maxes = []
		self._index = []
		self._offset = 0
		if iterable is not None:
			self._update(iterable)

	def __new__(cls, iterable=None, key=identity):
		return object.__new__(cls)

	@property
	def key(self):
		return self._key

	def clear(self):
		self._len = 0
		del self._lists[:]
		del self._keys[:]
		del self._maxes[:]
		del self._index[:]
	_clear = clear

	def add(self, value):
		_lists = self._lists
		_keys = self._keys
		_maxes = self._maxes
		key = self._key(value)
		if _maxes:
			pos = bisect_right(_maxes, key)
			if pos == len(_maxes):
				pos -= 1
				_lists[pos].append(value)
				_keys[pos].append(key)
				_maxes[pos] = key
			else:
				idx = bisect_right(_keys[pos], key)
				_lists[pos].insert(idx, value)
				_keys[pos].insert(idx, key)
			self._expand(pos)
		else:
			_lists.append([value])
			_keys.append([key])
			_maxes.append(key)
		self._len += 1

	def _expand(self, pos):
		_lists = self._lists
		_keys = self._keys
		_index = self._index
		if len(_keys[pos]) > self._load << 1:
			_maxes = self._maxes
			_load = self._load
			_lists_pos = _lists[pos]
			_keys_pos = _keys[pos]
			half = _lists_pos[_load:]
			half_keys = _keys_pos[_load:]
			del _lists_pos[_load:]
			del _keys_pos[_load:]
			_maxes[pos] = _keys_pos[-1]
			_lists.insert(pos + 1, half)
			_keys.insert(pos + 1, half_keys)
			_maxes.insert(pos + 1, half_keys[-1])
			del _index[:]
		elif _index:
			child = self._offset + pos
			while child:
				_index[child] += 1
				child = child - 1 >> 1
			_index[0] += 1

	def update(self, iterable):
		_lists = self._lists
		_keys = self._keys
		_maxes = self._maxes
		values = sorted(iterable, key=self._key)
		if _maxes:
			if len(values) * 4 >= self._len:
				values.extend(chain.from_iterable(_lists))
				values.sort(key=self._key)
				self._clear()
			else:
				_add = self.add
				for val in values:
					_add(val)
				return
		_load = self._load
		_lists.extend((values[pos:pos + _load] for pos in range(0, len(values), _load)))
		_keys.extend((list(map(self._key, _list)) for _list in _lists))
		_maxes.extend((sublist[-1] for sublist in _keys))
		self._len = len(values)
		del self._index[:]
	_update = update

	def __contains__(self, value):
		_maxes = self._maxes
		if not _maxes:
			return False
		key = self._key(value)
		pos = bisect_left(_maxes, key)
		if pos == len(_maxes):
			return False
		_lists = self._lists
		_keys = self._keys
		idx = bisect_left(_keys[pos], key)
		len_keys = len(_keys)
		len_sublist = len(_keys[pos])
		while True:
			if _keys[pos][idx] != key:
				return False
			if _lists[pos][idx] == value:
				return True
			idx += 1
			if idx == len_sublist:
				pos += 1
				if pos == len_keys:
					return False
				len_sublist = len(_keys[pos])
				idx = 0

	def discard(self, value):
		_maxes = self._maxes
		if not _maxes:
			return
		key = self._key(value)
		pos = bisect_left(_maxes, key)
		if pos == len(_maxes):
			return
		_lists = self._lists
		_keys = self._keys
		idx = bisect_left(_keys[pos], key)
		len_keys = len(_keys)
		len_sublist = len(_keys[pos])
		while True:
			if _keys[pos][idx] != key:
				return
			if _lists[pos][idx] == value:
				self._delete(pos, idx)
				return
			idx += 1
			if idx == len_sublist:
				pos += 1
				if pos == len_keys:
					return
				len_sublist = len(_keys[pos])
				idx = 0

	def remove(self, value):
		_maxes = self._maxes
		if not _maxes:
			raise ValueError('{0!r} not in list'.format(value))
		key = self._key(value)
		pos = bisect_left(_maxes, key)
		if pos == len(_maxes):
			raise ValueError('{0!r} not in list'.format(value))
		_lists = self._lists
		_keys = self._keys
		idx = bisect_left(_keys[pos], key)
		len_keys = len(_keys)
		len_sublist = len(_keys[pos])
		while True:
			if _keys[pos][idx] != key:
				raise ValueError('{0!r} not in list'.format(value))
			if _lists[pos][idx] == value:
				self._delete(pos, idx)
				return
			idx += 1
			if idx == len_sublist:
				pos += 1
				if pos == len_keys:
					raise ValueError('{0!r} not in list'.format(value))
				len_sublist = len(_keys[pos])
				idx = 0

	def _delete(self, pos, idx):
		_lists = self._lists
		_keys = self._keys
		_maxes = self._maxes
		_index = self._index
		keys_pos = _keys[pos]
		lists_pos = _lists[pos]
		del keys_pos[idx]
		del lists_pos[idx]
		self._len -= 1
		len_keys_pos = len(keys_pos)
		if len_keys_pos > self._load >> 1:
			_maxes[pos] = keys_pos[-1]
			if _index:
				child = self._offset + pos
				while child > 0:
					_index[child] -= 1
					child = child - 1 >> 1
				_index[0] -= 1
		elif len(_keys) > 1:
			if not pos:
				pos += 1
			prev = pos - 1
			_keys[prev].extend(_keys[pos])
			_lists[prev].extend(_lists[pos])
			_maxes[prev] = _keys[prev][-1]
			del _lists[pos]
			del _keys[pos]
			del _maxes[pos]
			del _index[:]
			self._expand(prev)
		elif len_keys_pos:
			_maxes[pos] = keys_pos[-1]
		else:
			del _lists[pos]
			del _keys[pos]
			del _maxes[pos]
			del _index[:]

	def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False):
		min_key = self._key(minimum) if minimum is not None else None
		max_key = self._key(maximum) if maximum is not None else None
		return self._irange_key(min_key=min_key, max_key=max_key, inclusive=inclusive, reverse=reverse)

	def irange_key(self, min_key=None, max_key=None, inclusive=(True, True), reverse=False):
		_maxes = self._maxes
		if not _maxes:
			return iter(())
		_keys = self._keys
		if min_key is None:
			min_pos = 0
			min_idx = 0
		elif inclusive[0]:
			min_pos = bisect_left(_maxes, min_key)
			if min_pos == len(_maxes):
				return iter(())
			min_idx = bisect_left(_keys[min_pos], min_key)
		else:
			min_pos = bisect_right(_maxes, min_key)
			if min_pos == len(_maxes):
				return iter(())
			min_idx = bisect_right(_keys[min_pos], min_key)
		if max_key is None:
			max_pos = len(_maxes) - 1
			max_idx = len(_keys[max_pos])
		elif inclusive[1]:
			max_pos = bisect_right(_maxes, max_key)
			if max_pos == len(_maxes):
				max_pos -= 1
				max_idx = len(_keys[max_pos])
			else:
				max_idx = bisect_right(_keys[max_pos], max_key)
		else:
			max_pos = bisect_left(_maxes, max_key)
			if max_pos == len(_maxes):
				max_pos -= 1
				max_idx = len(_keys[max_pos])
			else:
				max_idx = bisect_left(_keys[max_pos], max_key)
		return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
	_irange_key = irange_key

	def bisect_left(self, value):
		return self._bisect_key_left(self._key(value))

	def bisect_right(self, value):
		return self._bisect_key_right(self._key(value))
	bisect = bisect_right

	def bisect_key_left(self, key):
		_maxes = self._maxes
		if not _maxes:
			return 0
		pos = bisect_left(_maxes, key)
		if pos == len(_maxes):
			return self._len
		idx = bisect_left(self._keys[pos], key)
		return self._loc(pos, idx)
	_bisect_key_left = bisect_key_left

	def bisect_key_right(self, key):
		_maxes = self._maxes
		if not _maxes:
			return 0
		pos = bisect_right(_maxes, key)
		if pos == len(_maxes):
			return self._len
		idx = bisect_right(self._keys[pos], key)
		return self._loc(pos, idx)
	bisect_key = bisect_key_right
	_bisect_key_right = bisect_key_right

	def count(self, value):
		_maxes = self._maxes
		if not _maxes:
			return 0
		key = self._key(value)
		pos = bisect_left(_maxes, key)
		if pos == len(_maxes):
			return 0
		_lists = self._lists
		_keys = self._keys
		idx = bisect_left(_keys[pos], key)
		total = 0
		len_keys = len(_keys)
		len_sublist = len(_keys[pos])
		while True:
			if _keys[pos][idx] != key:
				return total
			if _lists[pos][idx] == value:
				total += 1
			idx += 1
			if idx == len_sublist:
				pos += 1
				if pos == len_keys:
					return total
				len_sublist = len(_keys[pos])
				idx = 0

	def copy(self):
		return self.__class__(self, key=self._key)
	__copy__ = copy

	def index(self, value, start=None, stop=None):
		_len = self._len
		if not _len:
			raise ValueError('{0!r} is not in list'.format(value))
		if start is None:
			start = 0
		if start < 0:
			start += _len
		if start < 0:
			start = 0
		if stop is None:
			stop = _len
		if stop < 0:
			stop += _len
		if stop > _len:
			stop = _len
		if stop <= start:
			raise ValueError('{0!r} is not in list'.format(value))
		_maxes = self._maxes
		key = self._key(value)
		pos = bisect_left(_maxes, key)
		if pos == len(_maxes):
			raise ValueError('{0!r} is not in list'.format(value))
		stop -= 1
		_lists = self._lists
		_keys = self._keys
		idx = bisect_left(_keys[pos], key)
		len_keys = len(_keys)
		len_sublist = len(_keys[pos])
		while True:
			if _keys[pos][idx] != key:
				raise ValueError('{0!r} is not in list'.format(value))
			if _lists[pos][idx] == value:
				loc = self._loc(pos, idx)
				if start <= loc <= stop:
					return loc
				elif loc > stop:
					break
			idx += 1
			if idx == len_sublist:
				pos += 1
				if pos == len_keys:
					raise ValueError('{0!r} is not in list'.format(value))
				len_sublist = len(_keys[pos])
				idx = 0
		raise ValueError('{0!r} is not in list'.format(value))

	def __add__(self, other):
		values = reduce(iadd, self._lists, [])
		values.extend(other)
		return self.__class__(values, key=self._key)
	__radd__ = __add__

	def __mul__(self, num):
		values = reduce(iadd, self._lists, []) * num
		return self.__class__(values, key=self._key)

	def __reduce__(self):
		values = reduce(iadd, self._lists, [])
		return (type(self), (values, self.key))

	@recursive_repr()
	def __repr__(self):
		type_name = type(self).__name__
		return '{0}({1!r}, key={2!r})'.format(type_name, list(self), self._key)

	def _check(self):
		try:
			assert self._load >= 4
			assert len(self._maxes) == len(self._lists) == len(self._keys)
			assert self._len == sum((len(sublist) for sublist in self._lists))
			for sublist in self._keys:
				for pos in range(1, len(sublist)):
					assert sublist[pos - 1] <= sublist[pos]
			for pos in range(1, len(self._keys)):
				assert self._keys[pos - 1][-1] <= self._keys[pos][0]
			for (val_sublist, key_sublist) in zip(self._lists, self._keys):
				assert len(val_sublist) == len(key_sublist)
				for (val, key) in zip(val_sublist, key_sublist):
					assert self._key(val) == key
			for pos in range(len(self._maxes)):
				assert self._maxes[pos] == self._keys[pos][-1]
			double = self._load << 1
			assert all((len(sublist) <= double for sublist in self._lists))
			half = self._load >> 1
			for pos in range(0, len(self._lists) - 1):
				assert len(self._lists[pos]) >= half
			if self._index:
				assert self._len == self._index[0]
				assert len(self._index) == self._offset + len(self._lists)
				for pos in range(len(self._lists)):
					leaf = self._index[self._offset + pos]
					assert leaf == len(self._lists[pos])
				for pos in range(self._offset):
					child = (pos << 1) + 1
					if child >= len(self._index):
						assert self._index[pos] == 0
					elif child + 1 == len(self._index):
						assert self._index[pos] == self._index[child]
					else:
						child_sum = self._index[child] + self._index[child + 1]
						assert child_sum == self._index[pos]
		except:
			traceback.print_exc(file=sys.stdout)
			print('len', self._len)
			print('load', self._load)
			print('offset', self._offset)
			print('len_index', len(self._index))
			print('index', self._index)
			print('len_maxes', len(self._maxes))
			print('maxes', self._maxes)
			print('len_keys', len(self._keys))
			print('keys', self._keys)
			print('len_lists', len(self._lists))
			print('lists', self._lists)
			raise
SortedListWithKey = SortedKeyList
import io
import os

def solve(N, M, K, books):
	A = []
	B = []
	common = []
	padding = SortedList()
	paddingSum = 0
	extras = SortedList()
	for (i, (t, a, b)) in enumerate(books):
		if a and b:
			common.append(t)
		elif a:
			A.append(t)
		elif b:
			B.append(t)
		else:
			extras.add(t)
	A.sort()
	B.sort()
	common.sort()
	prefA = [0]
	for t in A:
		prefA.append(prefA[-1] + t)
	prefB = [0]
	for t in B:
		prefB.append(prefB[-1] + t)
	prefC = [0]
	for t in common:
		prefC.append(prefC[-1] + t)
	cMin = max(0, K - len(A), K - len(B), 2 * K - M)
	cMax = min(K, len(common))
	if cMin > cMax:
		return -1
	for i in range(cMin, len(common)):
		extras.add(common[i])
	for i in range(K - cMin, len(A)):
		extras.add(A[i])
	for i in range(K - cMin, len(B)):
		extras.add(B[i])
	best = (float('inf'),)
	for c in range(cMin, cMax + 1):
		assert 0 <= c <= len(common)
		assert 0 <= K - c <= len(A)
		assert 0 <= K - c <= len(B)
		pad = M - c - (K - c) * 2
		assert pad >= 0
		while len(padding) < pad and extras:
			x = extras[0]
			extras.remove(x)
			padding.add(x)
			paddingSum += x
		while len(padding) > pad:
			x = padding[-1]
			padding.remove(x)
			paddingSum -= x
			extras.add(x)
		if len(padding) == pad:
			cost = prefC[c] + prefB[K - c] + prefA[K - c] + paddingSum
			best = min(best, (cost, c))
		assert c + (K - c) + (K - c) + len(padding) + len(extras) == N
		if padding and extras:
			assert padding[-1] <= extras[0]
		if 0 <= K - c - 1 < len(A):
			x = A[K - c - 1]
			if padding and x <= padding[-1]:
				padding.add(x)
				paddingSum += x
			else:
				extras.add(x)
		if 0 <= K - c - 1 < len(B):
			x = B[K - c - 1]
			if padding and x <= padding[-1]:
				padding.add(x)
				paddingSum += x
			else:
				extras.add(x)
		if c < len(common):
			x = common[c]
			if x in extras:
				extras.remove(x)
			elif x in padding:
				padding.remove(x)
				paddingSum -= x
	if best[0] == float('inf'):
		return -1
	needC = best[1]
	needA = K - needC
	needB = K - needC
	needPad = M - needC - needB - needA
	check = 0
	ans = []
	for (i, (t, a, b)) in sorted(enumerate(books), key=lambda ix: ix[1][0]):
		if a and b:
			if needC:
				needC -= 1
				ans.append(str(i + 1))
				check += t
				continue
		if a:
			if needA:
				needA -= 1
				ans.append(str(i + 1))
				check += t
				continue
		if b:
			if needB:
				needB -= 1
				ans.append(str(i + 1))
				check += t
				continue
		if needPad:
			needPad -= 1
			ans.append(str(i + 1))
			check += t
	assert len(ans) == M
	assert check == best[0]
	return str(best[0]) + '\n' + ' '.join((x for x in ans))
if False:
	import random
	random.seed(0)
	N = 2 * 10 ** 5
	for i in range(1):
		books = [[random.randint(1, 20), random.randint(0, 1), random.randint(0, 1)] for i in range(N)]
		solve(len(books), random.randint(1, 100), random.randint(1, 100), books)
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N, M, K) = [int(x) for x in input().split()]
books = [[int(x) for x in input().split()] for i in range(N)]
ans = solve(N, M, K, books)
print(ans)


from math import inf, log2

class SegmentTree:

	def __init__(self, array, func=max):
		self.n = len(array)
		self.size = 2 ** (int(log2(self.n - 1)) + 1) if self.n != 1 else 1
		self.func = func
		self.default = 0 if self.func != min else inf
		self.data = [self.default] * (2 * self.size)
		self.process(array)

	def process(self, array):
		self.data[self.size:self.size + self.n] = array
		for i in range(self.size - 1, -1, -1):
			self.data[i] = self.func(self.data[2 * i], self.data[2 * i + 1])

	def query(self, alpha, omega):
		if alpha == omega:
			return self.data[alpha + self.size]
		res = self.default
		alpha += self.size
		omega += self.size + 1
		while alpha < omega:
			if alpha & 1:
				res = self.func(res, self.data[alpha])
				alpha += 1
			if omega & 1:
				omega -= 1
				res = self.func(res, self.data[omega])
			alpha >>= 1
			omega >>= 1
		return res

	def update(self, index, value):
		index += self.size
		self.data[index] = value
		index >>= 1
		while index:
			self.data[index] = self.func(self.data[2 * index], self.data[2 * index + 1])
			index >>= 1
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import gcd, ceil

def pre(s):
	n = len(s)
	pi = [0] * n
	for i in range(1, n):
		j = pi[i - 1]
		while j and s[i] != s[j]:
			j = pi[j - 1]
		if s[i] == s[j]:
			j += 1
		pi[i] = j
	return pi

def prod(a):
	ans = 1
	for each in a:
		ans = ans * each
	return ans

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
	(n, k) = map(int, input().split())
	both = []
	anb = []
	bna = []
	for i in range(n):
		(t, a, b) = map(int, input().split())
		if a and b:
			both += [t]
		if a and (not b):
			anb += [t]
		if b and (not a):
			bna += [t]
	both = sorted(both)
	anb = sorted(anb)
	bna = sorted(bna)
	if not both:
		if min(len(anb), len(bna)) < k:
			print(-1)
		else:
			print(sum(anb[:k]) + sum(bna[:k]))
		continue
	if not anb or not bna:
		if len(both) < k:
			print(-1)
		else:
			print(sum(both[:k]))
		continue
	(l1, l2, l3) = (len(both), len(anb), len(bna))
	both = SegmentTree(both, func=lambda a, b: a + b)
	anb = SegmentTree(anb, func=lambda a, b: a + b)
	bna = SegmentTree(bna, func=lambda a, b: a + b)
	anss = inf
	for i in range(min(l1 + 1, k + 1)):
		ans = both.query(0, i - 1) if i else 0
		if min(l2, l3) >= k - i:
			if i != k:
				ans += anb.query(0, k - i - 1) + bna.query(0, k - i - 1)
			anss = min(anss, ans)
	print(anss if anss != inf else -1)


(n, k) = list(map(int, input().strip().split()))
list1 = []
list2 = []
list12 = []
list0 = []
for _ in range(n):
	(x, y, z) = list(map(int, input().strip().split()))
	if y == 1 and z == 1:
		list12.append(x)
	elif y == 1:
		list1.append(x)
	elif z == 1:
		list2.append(x)
list1.sort()
list2.sort()
loop = min(len(list1), len(list2))
for i in range(loop):
	list12.append(list1[i] + list2[i])
list12.sort()
if len(list12) < k:
	print(-1)
else:
	ans = 0
	for i in range(k):
		ans += list12[i]
	print(ans)


import sys
input = sys.stdin.readline
from math import ceil
(n, k) = map(int, input().split())
bob = []
alice = []
good = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1:
		if b == 1:
			good.append(t)
		else:
			alice.append(t)
	elif b == 1:
		bob.append(t)
alice.sort()
bob.sort()
good.sort()
ma = len(alice)
mb = len(bob)
mg = len(good)
ka = k
kb = k
T = 0
ia = 0
ib = 0
ig = 0
while ka > 0 and kb > 0 and (ig < mg) and (ia < ma) and (ib < mb):
	if good[ig] <= alice[ia] + bob[ib]:
		T += good[ig]
		ig += 1
	else:
		T += alice[ia] + bob[ib]
		ia += 1
		ib += 1
	ka -= 1
	kb -= 1
if ia == ma:
	while ka > 0 and ig < mg:
		T += good[ig]
		ig += 1
		kb -= 1
		ka -= 1
elif ib == mb:
	while kb > 0 and ig < mg:
		T += good[ig]
		ig += 1
		ka -= 1
		kb -= 1
else:
	while ka > 0 and ia < ma:
		T += alice[ia]
		ia += 1
		ka -= 1
	while kb > 0 and ib < mb:
		T += bob[ib]
		ib += 1
		kb -= 1
if ka > 0 or kb > 0:
	print(-1)
else:
	print(T)


from fractions import Fraction
import bisect
import os
import io
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
from queue import Queue

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())
mod = int(1000000000.0) + 7

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
t = 1
oo = []
zo = []
oz = []
for _ in range(t):
	(n, k) = rinput()
	for i in range(n):
		(t, a, b) = rinput()
		if a == 1 and b == 1:
			oo.append(t)
		elif a == 1:
			oz.append(t)
		elif b == 1:
			zo.append(t)
oo.sort()
zo.sort()
oz.sort()
poo = list(accumulate(oo))
pzo = list(accumulate(zo))
poz = list(accumulate(oz))
noo = len(oo)
nzo = len(zo)
noz = len(oz)
ans = float('inf')
for i in range(noo + 1):
	want = k - i
	if nzo >= want and noz >= want and (want > 0) and (i == 0):
		ans = min(ans, pzo[want - 1] + poz[want - 1])
	if nzo >= want and noz >= want and (i > 0) and (want > 0):
		ans = min(ans, poo[i - 1] + pzo[want - 1] + poz[want - 1])
	if want == 0 and i == k:
		ans = min(ans, poo[i - 1])
print(-1 if ans == float('inf') else ans)


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n
avl = AvlTree()

class SegmentTree1:

	def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] <= key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
(n, k) = map(int, input().split())
r = []
r1 = []
r2 = []
for i in range(n):
	(a, b, c) = map(int, input().split())
	if b == 1 and c == 1:
		r.append(a)
	elif b == 1:
		r1.append(a)
	elif c == 1:
		r2.append(a)
r1.sort()
r2.sort()
r.sort()
t = 0
t1 = 0
le = min(len(r1), len(r2))
if len(r) + min(len(r1), len(r2)) < k:
	print(-1)
	sys.exit()
ans = 0
for i in range(k):
	if t == le:
		t1 += 1
		ans += r[t1 - 1]
		continue
	if t1 == len(r):
		t += 1
		ans += r1[t - 1] + r2[t - 1]
		continue
	if r1[t] + r2[t] < r[t1]:
		t += 1
		ans += r1[t - 1] + r2[t - 1]
	else:
		t1 += 1
		ans += r[t1 - 1]
print(ans)


from heapq import heapify, heappop, heappush
import sys
input = sys.stdin.buffer.readline

def main():
	(n, k) = map(int, input().split())
	A = []
	B = []
	AorB = []
	C = []
	for __ in range(n):
		(t, a, b) = map(int, input().split())
		if a == b == 1:
			C.append(t)
		elif a == 1:
			A.append(t)
			AorB.append(t)
		elif b == 1:
			B.append(t)
			AorB.append(t)
	if len(A) + len(C) < k or len(B) + len(C) < k:
		print(-1)
		exit()
	A.sort()
	B.sort()
	C.sort()
	C = C[:min(k, len(C))]
	ans = 0
	nokori = k - len(C)
	for i in range(nokori):
		ans += A[i] + B[i]
	ab_idx = nokori
	while C and ab_idx < len(A) and (ab_idx < len(B)) and (C[-1] >= A[ab_idx] + B[ab_idx]):
		C.pop()
		ans += A[ab_idx] + B[ab_idx]
		ab_idx += 1
	ans += sum(C)
	print(ans)
main()


(n, k) = map(int, input().split())
t = []
a = []
b = []
for i in range(n):
	(t1, a1, b1) = map(int, input().split())
	if a1 == 1 and b1 == 1:
		t.append(t1)
	elif a1 == 1:
		a.append(t1)
	elif b1 == 1:
		b.append(t1)
a.sort()
b.sort()
k1 = min(len(a), len(b))
for i in range(k1):
	t.append(a[i] + b[i])
t.sort()
if len(t) < k:
	print('-1')
else:
	print(sum(t[:k]))


(n, k) = map(int, input().split())
t10 = []
t01 = []
t11 = []
for x in range(n):
	(t, a, b) = map(int, input().split())
	if a == 0 and b == 1:
		t01.append(t)
	elif a == 1 and b == 0:
		t10.append(t)
	elif a == 1 and b == 1:
		t11.append(t)
t10.sort()
t01.sort()
t11.sort()
for x in range(1, len(t01)):
	t01[x] += t01[x - 1]
for x in range(1, len(t10)):
	t10[x] += t10[x - 1]
for x in range(1, len(t11)):
	t11[x] += t11[x - 1]
t10 = [0] + t10
t01 = [0] + t01
t11 = [0] + t11
ans = []
for x in range(len(t11)):
	if k - x > len(t10) - 1 or k - x > len(t01) - 1:
		continue
	t = 0
	t += t11[x]
	t += t01[k - x]
	t += t10[k - x]
	ans.append(t)
	if x == k:
		break
if len(ans) == 0:
	print(-1)
else:
	print(min(ans))


(n, k) = map(int, input().split())
q1 = []
q2 = []
q3 = []
for i in range(n):
	(a, b, c) = map(int, input().split())
	if b == 1 and c == 0:
		q1.append(a)
	elif b == 0 and c == 1:
		q2.append(a)
	elif b == 1 and c == 1:
		q3.append(a)
q1.sort()
q2.sort()
for i in range(min(len(q1), len(q2))):
	q3.append(q1[i] + q2[i])
if len(q3) < k:
	print(-1)
else:
	q3.sort()
	print(sum(q3[:k]))


R = lambda : map(int, input().split())
s = sorted
(n, k) = R()
(_, u, v, w) = l = [[], [], [], []]
for _ in [0] * n:
	(t, a, b) = R()
	l[2 * a + b] += (t,)
a = (*map(sum, zip(s(u), s(v))), *w)
print(sum((s(a) + [-sum(a) - 1])[:k]))


(n, k) = map(int, input().split())
a = []
b = []
bb = []
x = []
cnta = 0
cntb = 0
for i in range(n):
	(t, p, q) = list(map(int, input().split()))
	t = [t, p, q]
	x.append(t)
	(t, p, q) = x[i]
	if p and q:
		bb.append(t)
		cnta += 1
		cntb += 1
	elif p:
		a.append(t)
		cnta += 1
	elif q:
		b.append(t)
		cntb += 1
a.sort()
b.sort()
if cnta >= k and cntb >= k:
	for i in range(min(len(a), len(b))):
		bb.append(a[i] + b[i])
	out = 0
	bb.sort()
	for i in range(k):
		out += bb[i]
	print(out)
else:
	print(-1)


from functools import cmp_to_key
from collections import deque
from heapq import heappush, heappop
from math import log, ceil
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def ii():
	return int(inp())

def li(lag=0):
	l = list(map(int, inp().split()))
	if lag != 0:
		for i in range(len(l)):
			l[i] += lag
	return l

def mi(lag=0):
	matrix = list()
	for i in range(n):
		matrix.append(li(lag))
	return matrix

def sli():
	return list(map(str, inp().split()))

def print_list(lista, space=' '):
	print(space.join(map(str, lista)))

class UnionFind:

	def __init__(self, n):
		self.parent = list(range(n))
		self.size = [1] * n
		self.num_sets = n

	def find(self, a):
		to_update = []
		while a != self.parent[a]:
			to_update.append(a)
			a = self.parent[a]
		for b in to_update:
			self.parent[b] = a
		return self.parent[a]

	def merge(self, a, b):
		a = self.find(a)
		b = self.find(b)
		if a == b:
			return
		if self.size[a] < self.size[b]:
			(a, b) = (b, a)
		self.num_sets -= 1
		self.parent[b] = a
		self.size[a] += self.size[b]

	def set_size(self, a):
		return self.size[self.find(a)]

	def __len__(self):
		return self.num_sets

def bisect_left(a, x):
	left = 0
	right = len(a)
	while left < right:
		mid = (left + right) // 2
		if a[mid] < x:
			left = mid + 1
		else:
			right = mid
	return left

def bisect_right(a, x):
	left = 0
	right = len(a)
	while left < right:
		mid = (left + right) // 2
		if a[mid] > x:
			right = mid
		else:
			left = mid + 1
	return left

def bisect_elements(a, x):
	return bisect_right(a, x) - bisect_left(a, x)

def custom_sort(lista):

	def cmp(x, y):
		if x + y > y + x:
			return 1
		else:
			return -1
	return sorted(lista, key=cmp_to_key(cmp))
MOD = 10 ** 9 + 7
maxN = 10 ** 5
FACT = [0] * maxN

def add(x, y):
	return (x + y) % MOD

def multiply(x, y):
	return x * y % MOD

def power(x, y):
	if y == 0:
		return 1
	elif y % 2:
		return multiply(x, power(x, y - 1))
	else:
		a = power(x, y // 2)
		return multiply(a, a)

def inverse(x):
	return power(x, MOD - 2)

def divide(x, y):
	return multiply(x, inverse(y))

def allFactorials():
	FACT[0] = 1
	for i in range(1, maxN):
		FACT[i] = multiply(i, FACT[i - 1])

def coeffBinom(n, k):
	if n < k:
		return 0
	return divide(FACT[n], multiply(FACT[k], FACT[n - k]))

def primes(N):
	smallest_prime = [1] * (N + 1)
	prime = []
	smallest_prime[0] = 0
	smallest_prime[1] = 0
	for i in range(2, N + 1):
		if smallest_prime[i] == 1:
			prime.append(i)
			smallest_prime[i] = i
		j = 0
		while j < len(prime) and i * prime[j] <= N:
			smallest_prime[i * prime[j]] = min(prime[j], smallest_prime[i])
			j += 1
	return (prime, smallest_prime)

def gcd(a, b):
	a = abs(a)
	b = abs(b)
	(s, t, r) = (0, 1, b)
	(old_s, old_t, old_r) = (1, 0, a)
	while r != 0:
		quotient = old_r // r
		(old_r, r) = (r, old_r - quotient * r)
		(old_s, s) = (s, old_s - quotient * s)
		(old_t, t) = (t, old_t - quotient * t)
	return (old_r, old_s, old_t)

def create_graph(n, m, undirected=1, unweighted=1):
	graph = [[] for i in range(n)]
	if unweighted:
		for i in range(m):
			[x, y] = li(lag=-1)
			graph[x].append(y)
			if undirected:
				graph[y].append(x)
	else:
		for i in range(m):
			[x, y, w] = li(lag=-1)
			w += 1
			graph[x].append([y, w])
			if undirected:
				graph[y].append([x, w])
	return graph

def create_tree(n, unweighted=1):
	children = [[] for i in range(n)]
	if unweighted:
		for i in range(n - 1):
			[x, y] = li(lag=-1)
			children[x].append(y)
			children[y].append(x)
	else:
		for i in range(n - 1):
			[x, y, w] = li(lag=-1)
			w += 1
			children[x].append([y, w])
			children[y].append([x, w])
	return children

def create_edges(m, unweighted=0):
	edges = list()
	if unweighted:
		for i in range(m):
			edges.append(li(lag=-1))
	else:
		for i in range(m):
			[x, y, w] = li(lag=-1)
			w += 1
			edges.append([w, x, y])
	return edges

def dist(tree, n, A, B=-1):
	s = [[A, 0]]
	(massimo, massimo_nodo) = (0, 0)
	distanza = -1
	v = [-1] * n
	while s:
		(el, dis) = s.pop()
		if dis > massimo:
			massimo = dis
			massimo_nodo = el
		if el == B:
			distanza = dis
		for child in tree[el]:
			if v[child] == -1:
				v[child] = 1
				s.append([child, dis + 1])
	return (massimo, massimo_nodo, distanza)

def diameter(tree):
	(_, foglia, _) = dist(tree, n, 0)
	(diam, _, _) = dist(tree, n, foglia)
	return diam

def dfs(graph, n, A):
	v = [-1] * n
	s = [[A, 0]]
	v[A] = 0
	while s:
		(el, dis) = s.pop()
		for child in graph[el]:
			if v[child] == -1:
				v[child] = dis + 1
				s.append([child, dis + 1])
	return v

def bfs(graph, n, A):
	v = [-1] * n
	s = deque()
	s.append([A, 0])
	v[A] = 0
	while s:
		(el, dis) = s.popleft()
		for child in graph[el]:
			if v[child] == -1:
				v[child] = dis + 1
				s.append([child, dis + 1])
	return v

def connected(graph, n):
	v = dfs(graph, n, 0)
	for el in v:
		if el == -1:
			return False
	return True

def topological(graph, n):
	indegree = [0] * n
	for el in range(n):
		for child in graph[el]:
			indegree[child] += 1
	s = deque()
	for el in range(n):
		if indegree[el] == 0:
			s.append(el)
	order = []
	while s:
		el = s.popleft()
		order.append(el)
		for child in graph[el]:
			indegree[child] -= 1
			if indegree[child] == 0:
				s.append(child)
	if n == len(order):
		return (False, order)
	else:
		return (True, [])

def bipartite(graph, n):
	color = [-1] * n
	color[0] = 0
	s = [0]
	while s:
		el = s.pop()
		for child in graph[el]:
			if color[child] == color[el]:
				return False
			if color[child] == -1:
				s.append(child)
			color[child] = 1 - color[el]
	return True

def dijkstra(graph, n, A):
	dist = [float('inf') for i in range(n)]
	prev = [-1 for i in range(n)]
	dist[A] = 0
	pq = []
	heappush(pq, [0, A])
	while pq:
		[d_v, v] = heappop(pq)
		if d_v != dist[v]:
			continue
		for (to, w) in graph[v]:
			if dist[v] + w < dist[to]:
				dist[to] = dist[v] + w
				prev[to] = v
				heappush(pq, [dist[to], to])
	return (dist, prev)

def dijkstra_0_1(graph, n, A):
	dist = [float('inf') for i in range(n)]
	dist[A] = 0
	p = deque()
	p.append(A)
	while p:
		v = p.popleft()
		for (to, w) in graph[v]:
			if dist[v] + w < dist[to]:
				dist[to] = dist[v] + w
			if w == 1:
				q.append(to)
			else:
				q.appendleft(to)
	return dist

def floyd_warshall(graph, n):
	dist = [[float('inf') for _ in range(n)] for _ in range(n)]
	for i in range(n):
		dist[i][i] = 0
		for (child, d) in graph[i]:
			dist[i][child] = d
			dist[child][i] = d
	for k in range(n):
		for i in range(n):
			for j in range(j):
				dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
	return dist

def minimum_spanning_tree(edges, n):
	edges = sorted(edges)
	union_find = UnionFind(n)
	used_edges = list()
	for (w, x, y) in edges:
		if union_find.find(x) != union_find.find(y):
			union_find.merge(x, y)
			used_edges.append([w, x, y])
	return used_edges

def parents_children_root_unrooted_tree(tree, n, root=0):
	q = deque()
	visited = [0] * n
	parent = [-1] * n
	children = [[] for i in range(n)]
	q.append(root)
	while q:
		all_done = 1
		visited[q[0]] = 1
		for child in tree[q[0]]:
			if not visited[child]:
				all_done = 0
				q.appendleft(child)
		if all_done:
			for child in tree[q[0]]:
				if parent[child] == -1:
					parent[q[0]] = child
					children[child].append(q[0])
			q.popleft()
	return (parent, children)

def all_longest_path_passing_from_node(parent, children, n):
	q = deque()
	visited = [len(children[i]) for i in range(n)]
	downwards = [[0, 0] for i in range(n)]
	upward = [1] * n
	longest_path = [1] * n
	for i in range(n):
		if not visited[i]:
			q.append(i)
			downwards[i] = [1, 0]
	while q:
		node = q.popleft()
		if parent[node] != -1:
			visited[parent[node]] -= 1
			if not visited[parent[node]]:
				q.append(parent[node])
		else:
			root = node
		for child in children[node]:
			downwards[node] = sorted([downwards[node][0], downwards[node][1], downwards[child][0] + 1], reverse=True)[0:2]
	s = [node]
	while s:
		node = s.pop()
		if parent[node] != -1:
			if downwards[parent[node]][0] == downwards[node][0] + 1:
				upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][1])
			else:
				upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][0])
		longest_path[node] = downwards[node][0] + downwards[node][1] + upward[node] - min([downwards[node][0], downwards[node][1], upward[node]]) - 1
		for child in children[node]:
			s.append(child)
	return longest_path

def finding_ancestors(parent, queries, n):
	steps = int(ceil(log(n, 2)))
	ancestors = [[-1 for i in range(n)] for j in range(steps)]
	ancestors[0] = parent
	for i in range(1, steps):
		for node in range(n):
			if ancestors[i - 1][node] != -1:
				ancestors[i][node] = ancestors[i - 1][ancestors[i - 1][node]]
	result = []
	for (node, k) in queries:
		ans = node
		if k >= n:
			ans = -1
		i = 0
		while k > 0 and ans != -1:
			if k % 2:
				ans = ancestors[i][ans]
			k = k // 2
			i += 1
		result.append(ans)
	return result

def prefix_sum(arr):
	r = [0] * (len(arr) + 1)
	for (i, el) in enumerate(arr):
		r[i + 1] = r[i] + el
	return r

def nearest_from_the_left_smaller_elements(arr):
	n = len(arr)
	res = [-1] * n
	s = []
	for (i, el) in enumerate(arr):
		while s and s[-1] >= el:
			s.pop()
		if s:
			res[i] = s[-1]
		s.append(el)
	return res

def sliding_window_minimum(arr, k):
	res = []
	q = deque()
	for (i, el) in enumerate(arr):
		while q and arr[q[-1]] >= el:
			q.pop()
		q.append(i)
		while q and q[0] <= i - k:
			q.popleft()
		if i >= k - 1:
			res.append(arr[q[0]])
	return res
(n, k) = li()
e = list()
a = list()
b = list()
for i in range(n):
	[t, ai, bi] = li()
	if ai == 1 and bi == 1:
		e.append(t)
	elif ai == 1:
		a.append(t)
	elif bi == 1:
		b.append(t)
presi = 0
tempo = 0
e = sorted(e)
a = sorted(a)
b = sorted(b)
d = list()
i = 0
while i < len(a) and i < len(b):
	d.append(a[i] + b[i])
	i += 1
if len(d) + len(e) < k:
	print(-1)
else:
	i = 0
	j = 0
	d.append(float('inf'))
	e.append(float('inf'))
	while i < len(e) and j < len(d) and (presi < k):
		if e[i] > d[j]:
			tempo += d[j]
			j += 1
		else:
			tempo += e[i]
			i += 1
		presi += 1
	print(tempo)


from collections import defaultdict, deque
rr = lambda : input()
rri = lambda : int(input())
rrm = lambda : list(map(int, input().split()))
INF = float('inf')

def solve(N, K, B):
	groups = defaultdict(list)
	for (time, alike, blike) in B:
		if alike and blike:
			groups['c'].append(time)
		elif alike:
			groups['a'].append(time)
		elif blike:
			groups['b'].append(time)
	for g in groups:
		groups[g] = sorted(groups[g], reverse=True)
	(a, b) = (0, 0)
	amt = 0
	while groups['a'] or groups['b'] or groups['c']:
		if not groups['a'] or not groups['b']:
			if not groups['c']:
				break
			amt += groups['c'].pop()
			a += 1
			b += 1
		elif not groups['c'] or groups['a'][-1] + groups['b'][-1] < groups['c'][-1]:
			amt += groups['a'].pop()
			amt += groups['b'].pop()
			a += 1
			b += 1
		else:
			amt += groups['c'].pop()
			a += 1
			b += 1
		if a == K and b == K:
			break
	if a < K or b < K:
		return -1
	return amt
	if aread < K or bread < K:
		return -1
	return totaltime + atotal + btotal
(n, k) = rrm()
books = []
for _ in range(n):
	(time, a, b) = rrm()
	books.append((time, a, b))
print(solve(n, k, books))


(n, k) = map(int, input().split())
(a, b, c) = ([], [], [])
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x == y == 1:
		c.append(t)
	elif x == 1:
		a.append(t)
	elif y == 1:
		b.append(t)
a.sort()
b.sort()
for i in range(min(len(a), len(b))):
	c.append(a[i] + b[i])
c.sort()
if len(c) < k:
	print(-1)
else:
	print(sum(c[:k]))


(n, k) = [int(x) for x in input().split()]
res = 0
pick = 0
both = []
alice = []
bob = []
for i in range(n):
	(t, a, b) = [int(x) for x in input().split()]
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1 and b == 0:
		alice.append(t)
	elif a == 0 and b == 1:
		bob.append(t)
alice.sort()
bob.sort()
both.sort()
(n1, n2, n3) = (len(both), len(alice), len(bob))
(i, j, l) = (0, 0, 0)
while i < n1 and j < n2 and (l < n3):
	if both[i] <= alice[j] + bob[l]:
		res += both[i]
		i += 1
		pick += 1
		if pick == k:
			break
	else:
		res += alice[j] + bob[l]
		j += 1
		l += 1
		pick += 1
		if pick == k:
			break
if j >= n2 or l >= n3:
	while i < n1:
		res += both[i]
		i += 1
		pick += 1
		if pick == k:
			break
elif i >= n1:
	while j < n2 and l < n3:
		res += alice[j] + bob[l]
		j += 1
		l += 1
		pick += 1
		if pick == k:
			break
if pick == k:
	print(res)
else:
	print(-1)


(n, k) = map(int, input().split())
(v1, v2, v12) = ([], [], [])
for _ in range(n):
	(t, l1, l2) = map(int, input().split())
	if l1 == 1 and l2 == 1:
		v12.append(t)
	elif l1 == 1:
		v1.append(t)
	elif l2 == 1:
		v2.append(t)
v1.sort()
v2.sort()
v12.sort()
(x, y, z) = (0, 0, 0)
ans = 0
sb = k - min(len(v1), len(v2))
sb = sb if sb > 0 else 0
k -= sb
if sb > len(v12):
	print(-1)
else:
	for z in range(sb):
		ans += v12[z]
	z = sb
	while k > 0 and z < len(v12):
		if v12[z] <= v1[x] + v2[y]:
			ans += v12[z]
			z += 1
		else:
			ans += v1[x] + v2[y]
			x += 1
			y += 1
		k -= 1
	if k <= len(v1) - x and k <= len(v2) - y:
		while k > 0:
			ans += v1[x] + v2[y]
			x += 1
			y += 1
			k -= 1
		print(ans)
	else:
		print(-1)


from collections import deque
(n, k) = map(int, input().split())
(s, s1, s2) = (deque(), deque(), deque())
while n:
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		s.append(t)
	if a == 1 and b == 0:
		s1.append(t)
	if a == 0 and b == 1:
		s2.append(t)
	n -= 1
s = deque(sorted(s))
s1 = deque(sorted(s1))
s2 = deque(sorted(s2))
(x, y, t) = (0, 0, 0)
while len(s) and len(s1) and len(s2):
	if x == k or y == k:
		break
	if s[0] < s1[0] + s2[0]:
		x += 1
		y += 1
		t += s[0]
		s.popleft()
	else:
		t += s1[0] + s2[0]
		x += 1
		y += 1
		s1.popleft()
		s2.popleft()
if x != k and y != k and (len(s1) == 0):
	while x != k and y != k and (len(s) != 0):
		x += 1
		y += 1
		t += s[0]
		s.popleft()
if x != k and y != k and (len(s2) == 0):
	while x != k and y != k and (len(s) != 0):
		x += 1
		y += 1
		t += s[0]
		s.popleft()
if x != k:
	while len(s1) and x != k:
		t += s1[0]
		s1.popleft()
		x += 1
if y != k:
	while len(s2) and y != k:
		t += s2[0]
		s2.popleft()
		y += 1
if x == k and y == k:
	print(t)
else:
	print('-1')


import sys, os
from io import BytesIO, IOBase
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(stdin, stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def ceil(a, b):
	return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
(n, k) = mp()
(a, b, ab) = l2d(3, 1, inf)
for i in range(n):
	(x, y, z) = mp()
	if y == z == 1:
		ab.append(x)
	elif y == 1:
		a.append(x)
	elif z == 1:
		b.append(x)
if min(len(b), len(a)) + len(ab) - 2 < k:
	print(-1)
	exit()
a.sort(reverse=True)
b.sort(reverse=True)
ab.sort(reverse=True)
ans = 0
i = 0
while i < k:
	(x, y, z) = (a[-1], b[-1], ab[-1])
	if x + y < z:
		ans += a.pop() + b.pop()
	else:
		ans += ab.pop()
	i += 1
print(ans)


(n, k) = map(int, input().split())
time = []
a = []
b = []
count_a = 0
count_b = 0
for i in range(n):
	(t, a1, b1) = map(int, input().split())
	time.append(t)
	a.append(a1)
	b.append(b1)
	if a1 == 1:
		count_a += 1
	if b1 == 1:
		count_b += 1
if count_a < k or count_b < k:
	print(-1)
else:
	both = []
	a_not_b = []
	b_not_a = []
	for i in range(n):
		if a[i] == 1 and b[i] == 1:
			both.append(time[i])
		elif a[i] == 1 and b[i] == 0:
			a_not_b.append(time[i])
		elif a[i] == 0 and b[i] == 1:
			b_not_a.append(time[i])
	a_not_b.sort()
	b_not_a.sort()
	both_len = len(both)
	a_not_b_len = len(a_not_b)
	b_not_a_len = len(b_not_a)
	final = []
	req_len = min(a_not_b_len, b_not_a_len)
	for i in range(req_len):
		final.append(a_not_b[i] + b_not_a[i])
	final.extend(both)
	final.sort()
	if len(final) < k:
		print(-1)
	else:
		ans = 0
		for i in range(k):
			ans += final[i]
		print(ans)


import heapq
(n, k) = map(int, input().split())
(x, y, z) = ([], [], [])
heapq.heapify(x)
heapq.heapify(y)
heapq.heapify(z)
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == b == 1:
		heapq.heappush(x, t)
	elif a == 1:
		heapq.heappush(y, t)
	elif b == 1:
		heapq.heappush(z, t)
(lx, ly, lz) = (len(x), len(y), len(z))
(u, v) = (len(x), min(len(y), len(z)))
ans = 0
if u + v >= k:
	(i, j) = (0, 0)
	for _ in range(k):
		if i < u and j < v:
			if x[0] <= y[0] + z[0]:
				ans += heapq.heappop(x)
				i += 1
			else:
				ans += heapq.heappop(y) + heapq.heappop(z)
				j += 1
		elif i < u:
			ans += heapq.heappop(x)
			i += 1
		elif j < v:
			ans += heapq.heappop(y) + heapq.heappop(z)
			j += 1
else:
	ans = -1
print(ans)


from collections import deque
from operator import itemgetter
from sys import stdin, stdout
int_in = lambda : int(stdin.readline())
arr_in = lambda : [int(x) for x in stdin.readline().split()]
mat_in = lambda rows: [arr_in() for _ in range(rows)]
str_in = lambda : stdin.readline().strip()
out = lambda o: stdout.write('{}\n'.format(o))
arr_out = lambda o: out(' '.join(map(str, o)))
bool_out = lambda o: out('YES' if o else 'NO')
tests = lambda : range(1, int_in() + 1)
case_out = lambda i, o: out('Case #{}: {}'.format(i, o))

def solve(n, k, books):
	alice_books = list(sorted(filter(lambda x: x[1] == 1 and x[2] == 0, books), key=itemgetter(0)))[:k]
	bob_books = list(sorted(filter(lambda x: x[1] == 0 and x[2] == 1, books), key=itemgetter(0)))[:k]
	shared_books = list(sorted(filter(lambda x: x[1] == 1 and x[2] == 1, books), key=itemgetter(0)))[:k]
	have = min(len(alice_books), len(bob_books))
	need = k - have
	using_shared_books = []
	if need > 0:
		if len(shared_books) < need:
			return -1
		alice_books = alice_books[:have]
		bob_books = bob_books[:have]
		using_shared_books = shared_books[:need]
		shared_books = shared_books[need:]
	shared_books = deque(shared_books)
	if have > 0:
		while len(alice_books) > 0 and len(bob_books) > 0 and (len(shared_books) > 0) and (alice_books[-1][0] + bob_books[-1][0] > shared_books[0][0]):
			using_shared_books.append(shared_books[0])
			alice_books.pop()
			bob_books.pop()
			shared_books.popleft()
	if len(alice_books) + len(using_shared_books) != k:
		return -1
	if len(bob_books) + len(using_shared_books) != k:
		return -1
	result = 0
	for item in alice_books:
		result += item[0]
	for item in bob_books:
		result += item[0]
	for item in using_shared_books:
		result += item[0]
	return result
(n, k) = arr_in()
books = mat_in(n)
out(solve(n, k, books))


(n, k) = map(int, input().split())
d = {'a': [], 'b': [], 'c': []}
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if (a, b) == (1, 0):
		d['a'].append(t)
	if (a, b) == (0, 1):
		d['b'].append(t)
	if (a, b) == (1, 1):
		d['c'].append(t)
d['a'].sort()
d['b'].sort()
d['c'].sort()
a = d['a']
b = d['b']
c = d['c']
a1 = [0]
b1 = [0]
c1 = [0]
num = 0
for el in a:
	num += el
	a1.append(num)
num = 0
for el in b:
	num += el
	b1.append(num)
num = 0
for el in c:
	num += el
	c1.append(num)
if len(a) + len(c) < k or len(b) + len(c) < k:
	print(-1)
else:
	times = []
	i = 0
	while i <= k:
		try:
			temp = c1[i] + a1[k - i] + b1[k - i]
			times.append(temp)
		except IndexError:
			pass
		finally:
			i += 1
	print(min(times))


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
(a, b, ab) = ([], [], [])
(prea, preb, preab) = ([0], [0], [0])
ans = []
for _ in range(n):
	(t1, t2, t3) = map(int, input().split())
	if t2 == t3 == 1:
		ab.append(t1)
	elif t2 == 1:
		a.append(t1)
	elif t3 == 1:
		b.append(t1)
ab.sort()
a.sort()
b.sort()
(na, nb, nab) = (len(a), len(b), len(ab))
if nab + min(na, nb) < k:
	print(-1)
	sys.exit()
if na:
	for x in a:
		prea.append(prea[-1] + x)
if nb:
	for x in b:
		preb.append(preb[-1] + x)
if nab:
	for x in ab:
		preab.append(preab[-1] + x)
if na == 0 or nb == 0:
	if k <= nab:
		print(preab[k])
	else:
		print(-1)
else:
	for x in range(k + 1):
		if nab >= x and na >= k - x and (nb >= k - x):
			ans.append(preab[x] + prea[k - x] + preb[k - x])
	if len(ans) == 0:
		print(-1)
	else:
		print(min(ans))


(n, k) = map(int, input().split())
books = [list(map(int, input().split())) for _ in range(n)]
new_books = {str(i // 2) + str(i % 2): [0] for i in range(4)}
for book in books:
	new_books[str(book[1]) + str(book[2])].append(book[0])
for book in new_books.keys():
	new_books[book].sort()
	for i in range(1, len(new_books[book])):
		new_books[book][i] += new_books[book][i - 1]
ans = int(1e+18)
for taken in range(k + 1):
	if len(new_books['11']) > taken and len(new_books['10']) > k - taken and (len(new_books['01']) > k - taken):
		ans = min(ans, new_books['11'][taken] + new_books['10'][k - taken] + new_books['01'][k - taken])
print(ans if ans != int(1e+18) else -1)


(n, k) = [int(x) for x in input().strip().split()]
vec = []
for _ in range(n):
	vec.append([int(x) for x in input().split()])
vec.sort()
f1 = f2 = f3 = 0
minsum = 0
count = 0
min_12 = min_3 = 0
flag12 = flag3 = True
while (f3 <= n - 1 or (f1 <= n - 1 and f2 <= n - 1)) and count < k:
	while f3 <= n - 1:
		if vec[f3][1] == 1 and vec[f3][2] == 1:
			break
		f3 += 1
	if f3 <= n - 1:
		min_3 = vec[f3][0]
	else:
		flag3 = False
	while f2 <= n - 1:
		if vec[f2][1] == 1 and vec[f2][2] == 0:
			break
		f2 += 1
	while f1 <= n - 1:
		if vec[f1][1] == 0 and vec[f1][2] == 1:
			break
		f1 += 1
	if f1 <= n - 1 and f2 <= n - 1:
		min_12 = vec[f1][0] + vec[f2][0]
	else:
		flag12 = False
	if flag12 and flag3:
		count += 1
		if min_3 <= min_12:
			f3 += 1
			minsum += min_3
		else:
			f1 += 1
			f2 += 1
			minsum += min_12
	elif flag12:
		count += 1
		f1 += 1
		f2 += 1
		minsum += min_12
	elif flag3:
		count += 1
		f3 += 1
		minsum += min_3
if count == k:
	print(minsum)
else:
	print(-1)


(n, k) = [int(x) for x in input().split()]
(alice, bob, both) = ([], [], [])
for i in range(n):
	(t, a, b) = [int(x) for x in input().split()]
	if a == 0 and b == 0:
		continue
	if a & 1 and b & 1:
		both.append(t)
		continue
	if a & 1:
		alice.append(t)
	else:
		bob.append(t)
alice.sort()
bob.sort()
for i in range(min(len(alice), len(bob))):
	both.append(alice[i] + bob[i])
if len(both) < k:
	print(-1)
else:
	print(sum(sorted(both)[:k]))


def main():
	(n, k) = map(int, input().split())
	(a, b, both) = ([], [], [])
	for i in range(n):
		(nt, na, nb) = map(int, input().split())
		if na == nb == 1:
			both.append(nt)
		elif na == 1 and nb == 0:
			a.append(nt)
		elif na == 0 and nb == 1:
			b.append(nt)
	a.sort()
	b.sort()
	for i in range(min(len(a), len(b))):
		both.append(a[i] + b[i])
	both.sort()
	if len(both) < k:
		print(-1)
	else:
		print(sum(both[:k]))
main()


(n, k) = map(int, input().split())
a = []
b = []
comman = []
a_ = []
b_ = []
for _ in range(n):
	(t, ai, bi) = map(int, input().split())
	a_.append(ai)
	b_.append(bi)
	if ai == 1 and bi == 1:
		comman.append(t)
	elif ai == 1:
		a.append(t)
	elif bi == 1:
		b.append(t)
a.sort()
b.sort()
if a_.count(1) < k or b_.count(1) < k:
	print(-1)
else:
	s = 0
	m = min(len(a), len(b))
	for i in range(m):
		comman.append(a[i] + b[i])
	comman.sort()
	print(sum(comman[:k]))


(n, k) = list(map(int, input().split()))
both = []
a = []
b = []
for item in range(n):
	buff = list(map(int, input().split()))
	if buff[1] == 1 and buff[2] == 1:
		both.append(buff[0])
	elif buff[1] == 1:
		a.append(buff[0])
	elif buff[2] == 1:
		b.append(buff[0])
both.sort()
a.sort()
b.sort()
rez = 0
both_ind = 0
tog_ind = 0
while k > 0:
	if len(a) - tog_ind > 0 and len(b) - tog_ind > 0:
		if len(both) - both_ind > 0:
			if a[tog_ind] + b[tog_ind] < both[both_ind]:
				rez += a[tog_ind] + b[tog_ind]
				k -= 1
				tog_ind += 1
			else:
				rez += both[both_ind]
				k -= 1
				both_ind += 1
		else:
			k -= 1
			rez += a[tog_ind] + b[tog_ind]
			tog_ind += 1
	elif len(both) - both_ind > 0:
		k -= 1
		rez += both[both_ind]
		both_ind += 1
	else:
		print(-1)
		exit()
print(rez)


(n, k) = map(int, input().split())
ans = []
c1 = 0
c2 = 0
for i in range(n):
	z = list(map(int, input().split()))
	if z[1] == 1:
		c1 += 1
	if z[2] == 1:
		c2 += 1
	ans.append(z)
if min(c1, c2) < k:
	print(-1)
else:
	a0 = []
	a1 = []
	a2 = []
	for i in range(len(ans)):
		if ans[i][1] == 1 and ans[i][2] == 1:
			a0.append(ans[i])
		elif ans[i][1] == 1 and ans[i][2] == 0:
			a1.append(ans[i])
		elif ans[i][1] == 0 and ans[i][2] == 1:
			a2.append(ans[i])
	p0 = 0
	p1 = 0
	p2 = 0
	c1 = 0
	c2 = 0
	a0.sort()
	a1.sort()
	a2.sort()
	total = 0
	while c1 < k and c2 < k:
		if p0 < len(a0) and p1 < len(a1) and (p2 < len(a2)) and (a0[p0][0] <= a1[p1][0] + a2[p2][0]):
			total += a0[p0][0]
			c1 += 1
			c2 += 1
			p0 += 1
		else:
			if p1 < len(a1) and p2 < len(a2):
				total += a1[p1][0] + a2[p2][0]
				c1 += 1
				c2 += 1
				p1 += 1
				p2 += 1
				continue
			if p1 == len(a1) or p2 == len(a2):
				total += a0[p0][0]
				c1 += 1
				c2 += 1
				p0 += 1
	print(total)


(n, k) = input().split()
(n, k) = (int(n), int(k))
both = []
ali = []
bob = []
while n > 0:
	(t, a, b) = input().split()
	(t, a, b) = (int(t), int(a), int(b))
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1:
		ali.append(t)
	elif b == 1:
		bob.append(t)
	n -= 1
ans = 0
both.sort(reverse=True)
ali.sort(reverse=True)
bob.sort(reverse=True)
if len(both) + min(len(ali), len(bob)) < k:
	print(-1)
else:
	while k > 0:
		if len(both) == 0 or (len(ali) * len(bob) > 0 and ali[-1] + bob[-1] <= both[-1]):
			x = ali.pop(-1)
			y = bob.pop(-1)
			ans += x + y
		else:
			x = both.pop(-1)
			ans += x
		k -= 1
	print(ans)


import heapq
(n, k) = map(int, input().rstrip().split())
inn = []
inb = []
inc = []
for i in range(n):
	(a, b, c) = map(int, input().rstrip().split())
	if b == 0 and c == 0:
		continue
	elif b == 1 and c == 0:
		inb.append(a)
	elif b == 0 and c == 1:
		inc.append(a)
	else:
		inn.append(a)
heapq.heapify(inb)
heapq.heapify(inc)
heapq.heapify(inn)
ans = 0
while k > 0:
	if len(inb) and len(inc) and len(inn):
		if inb[0] + inc[0] < inn[0]:
			k1 = heapq.heappop(inb)
			k2 = heapq.heappop(inc)
			k -= 1
			ans += k1 + k2
		else:
			k1 = heapq.heappop(inn)
			ans += k1
			k -= 1
	elif len(inb) and len(inc):
		k1 = heapq.heappop(inb)
		k2 = heapq.heappop(inc)
		k -= 1
		ans += k1 + k2
	elif len(inn):
		k1 = heapq.heappop(inn)
		ans += k1
		k -= 1
	else:
		bool = False
		break
if bool == True or k == 0:
	print(ans)
else:
	print(-1)


def books(alice, bob, both, k, n):
	if len(alice) + len(both) < k or len(both) + len(bob) < k:
		return -1
	alice = sorted(alice)
	bob = sorted(bob)
	for i in range(min(len(alice), len(bob))):
		both.append(alice[i] + bob[i])
	return sum(sorted(both)[:k])
(a, b, c) = ([], [], [])
(x, y) = map(int, input().strip().split())
for i in range(x):
	(t, alice, bob) = map(int, input().strip().split())
	if alice and bob:
		c.append(t)
	elif alice:
		a.append(t)
	elif bob:
		b.append(t)
print(books(a, b, c, y, x))


(n, k) = map(int, input().split())
al = []
bo = []
ab = []
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		ab.append(t)
	elif a == 1:
		al.append(t)
	elif b == 1:
		bo.append(t)
al.sort()
bo.sort()
for i in range(min(len(al), len(bo))):
	ab.append(al[i] + bo[i])
ab.sort()
if len(ab) < k:
	print(-1)
else:
	print(sum(ab[:k]))


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
B = [tuple(map(int, input().split())) for _ in range(n)]
FB = []
AB = []
BB = []
for (t, a, b) in B:
	if a and b:
		FB.append(t)
	elif a:
		AB.append(t)
	elif b:
		BB.append(t)
AB.sort()
BB.sort()
for (t1, t2) in zip(AB, BB):
	FB.append(t1 + t2)
FB.sort()
if len(FB) < k:
	print(-1)
else:
	print(sum(FB[:k]))


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def fi():
	return float(input())

def si():
	return input()

def msi():
	return map(str, input().split())

def mi():
	return map(int, input().split())

def li():
	return list(mi())

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
mod = 1000000007
from math import log, log2, sqrt, factorial, cos, tan, sin, radians, ceil, floor
import bisect
from decimal import *
abc = 'abcdefghijklmnopqrstuvwxyz'
pi = 3.141592653589793

def main():
	(n, k) = mi()
	l = []
	l1 = []
	l2 = []
	for i in range(n):
		(x, y, z) = mi()
		if y and z:
			l.append(x)
		elif y:
			l1.append(x)
		elif z:
			l2.append(x)
	l1.sort()
	l2.sort()
	for i in range(min(len(l1), len(l2))):
		l.append(l1[i] + l2[i])
	l.sort()
	if len(l) < k:
		print(-1)
	else:
		ans = sum(l[0:k])
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
both = []
alice = []
bob = []
for _ in range(n):
	(c, a, b) = map(int, input().split())
	if a and b:
		both.append(c)
	elif a:
		alice.append(c)
	elif b:
		bob.append(c)
alice.sort()
bob.sort()
for (a, b) in zip(alice, bob):
	both.append(a + b)
both.sort()
if len(both) < k:
	print(-1)
else:
	print(sum(both[:k]))


from math import *
from collections import *
from bisect import *
import sys
input = sys.stdin.readline
t = 1
while t:
	t -= 1
	(n, k1) = map(int, input().split())
	oo = []
	al = []
	bob = []
	for i in range(n):
		a = list(map(int, input().split()))
		if a[-1] == a[-2] == 1:
			oo.append(a[0])
		elif a[-1] == 0 and a[-2] == 1:
			al.append(a[0])
		elif a[-1] == 1 and a[-2] == 0:
			bob.append(a[0])
	oo.sort()
	bob.sort()
	al.sort()
	(i, j, k) = (0, 0, 0)
	(ak, bk) = (k1, k1)
	rr = 0
	(l1, l2, l3) = (len(oo), len(al), len(bob))
	gb = 0
	while (ak > 0 or bk > 0) and (i < l1 or j < l2 or k < l3):
		if gb > n:
			break
		if i < l1:
			if j < l2 and k < l3:
				if oo[i] <= bob[k] + al[j]:
					ak -= 1
					bk -= 1
					rr += oo[i]
					i += 1
				elif bk <= 0:
					if oo[i] <= al[j]:
						rr += oo[i]
						i += 1
						ak -= 1
						bk -= 1
					else:
						rr += al[j]
						j += 1
						ak -= 1
				elif ak <= 0:
					if oo[i] <= bob[k]:
						rr += oo[i]
						i += 1
						ak -= 1
						bk -= 1
					else:
						rr += bob[k]
						bk -= 1
						k += 1
				else:
					rr += bob[k] + al[j]
					k += 1
					j += 1
					ak -= 1
					bk -= 1
			elif j < l2 and k >= l3:
				if bk <= 0:
					if oo[i] <= al[j]:
						rr += oo[i]
						ak -= 1
						bk -= 1
						i += 1
					else:
						rr += al[j]
						j += 1
						ak -= 1
				else:
					rr += oo[i]
					i += 1
					ak -= 1
					bk -= 1
			elif j >= l2 and k < l3:
				if ak <= 0:
					if oo[i] <= bob[k]:
						rr += oo[i]
						i += 1
						bk -= 1
						ak -= 1
					else:
						rr += bob[k]
						k += 1
						bk -= 1
				else:
					rr += oo[i]
					i += 1
					ak -= 1
					bk -= 1
			else:
				rr += oo[i]
				i += 1
				ak -= 1
				bk -= 1
		else:
			if ak > 0 and j < l2:
				rr += al[j]
				j += 1
				ak -= 1
			if bk > 0 and k < l3:
				rr += bob[k]
				k += 1
				bk -= 1
		gb += 1
	if ak <= 0 and bk <= 0:
		print(rr)
	else:
		print(-1)


from collections import defaultdict as dd
import sys
input = sys.stdin.readline
(n, kk) = map(int, input().split())
l = []
ans = 0
for i in range(n):
	(time, a, b) = map(int, input().split())
	l.append((time, a, b))
l.sort()
la = []
lb = []
do = []
for i in l:
	(time, a, b) = i
	if a and b:
		do.append(time)
	elif a:
		la.append(time)
	elif b:
		lb.append(time)
i = 0
j = 0
k = 0
ca = kk
cb = kk
while ca and cb:
	if i < len(la):
		if j < len(lb):
			if k < len(do):
				if la[i] + lb[j] <= do[k]:
					ans += la[i]
					ans += lb[j]
					i += 1
					j += 1
					ca -= 1
					cb -= 1
				else:
					ans += do[k]
					k += 1
					ca -= 1
					cb -= 1
			else:
				ans += la[i]
				ans += lb[j]
				i += 1
				j += 1
				ca -= 1
				cb -= 1
		elif k < len(do):
			ans += do[k]
			k += 1
			ca -= 1
			cb -= 1
		else:
			break
	elif k < len(do):
		ans += do[k]
		k += 1
		ca -= 1
		cb -= 1
	else:
		break
if ca:
	while ca and i < len(la) and (k < len(do)):
		if la[i] <= do[k]:
			ans += la[i]
			i += 1
			ca -= 1
		else:
			ans += do[k]
			k += 1
			ca -= 1
	while ca and i < len(la):
		ans += la[i]
		i += 1
		ca -= 1
	while ca and k < len(do):
		ans += do[k]
		k += 1
		ca -= 1
elif cb:
	i = j
	la = lb
	ca = cb
	while ca and i < len(la) and (k < len(do)):
		if la[i] <= do[k]:
			ans += la[i]
			i += 1
			ca -= 1
		else:
			ans += do[k]
			k += 1
			ca -= 1
	while ca and i < len(la):
		ans += la[i]
		i += 1
		ca -= 1
	while ca and k < len(do):
		ans += do[k]
		k += 1
		ca -= 1
	cb = ca
if ca or cb:
	print(-1)
else:
	print(ans)


from typing import List
from heapq import heappop, heappush

def readingBooks_easy(n: int, k: int, books: List[int]) -> int:
	books.sort(key=lambda x: x[0])
	alice = []
	bob = []
	alice_and_bob = []
	for i in range(len(books)):
		if books[i][1] == 1 and books[i][2] == 0:
			alice.append(books[i][0])
		elif books[i][1] == 0 and books[i][2] == 1:
			bob.append(books[i][0])
		elif books[i][1] == 1 and books[i][2] == 1:
			alice_and_bob.append(books[i][0])
	alice_or_bob = []
	for i in range(min(len(alice), len(bob))):
		alice_or_bob.append(alice[i] + bob[i])
	heap = []
	for i in range(len(alice_and_bob)):
		heappush(heap, alice_and_bob[i])
	for i in range(len(alice_or_bob)):
		heappush(heap, alice_or_bob[i])
	ans = 0
	for _ in range(k):
		if heap:
			ans += heappop(heap)
		else:
			return -1
	return ans
inputs = list(map(int, input().split(' ')))
n = inputs[0]
k = inputs[1]
books = []
for _ in range(n):
	books.append(list(map(int, input().split(' '))))
print(readingBooks_easy(n, k, books))


(n, k) = map(int, input().split())
a = []
b = []
c = []
d = []
for i in range(n):
	(x, y, z) = map(int, input().split())
	if y == 0 and z == 0:
		d.append(x)
	elif y == 1 and z == 1:
		a.append(x)
	elif y == 0 and z == 1:
		c.append(x)
	else:
		b.append(x)
b.sort()
c.sort()
m = min(len(b), len(c))
for i in range(m):
	a.append(b[i] + c[i])
a.sort()
if len(a) < k:
	print('-1')
else:
	print(sum(a[:k]))


(n, k) = input().split(' ')
(n, k) = (int(n), int(k))
S = []
for i in range(n):
	S.append(input().split(' '))
A = []
B = []
C = []
for i in S:
	if i[1] == '1' and i[2] == '1':
		C.append(int(i[0]))
	elif i[1] == '1' and i[2] == '0':
		A.append(int(i[0]))
	elif i[1] == '0' and i[2] == '1':
		B.append(int(i[0]))
m = min(len(A), len(B))
if len(C) + m < k:
	print(-1)
else:
	A.sort()
	B.sort()
	for i in range(m):
		C.append(A[i] + B[i])
	ans = 0
	C.sort()
	for i in range(k):
		ans += C[i]
	print(ans)


import sys

def cta(t, p, r):
	global ana, iva, an
	ana[iva[t][p][1]] ^= True
	an += iva[t][p][0] * r
s = sys.stdin.readline().split()
(n, m, k) = (int(s[0]), int(s[1]), int(s[2]))
if k != 10220 or m != 164121:
	all = []
	All = []
	Alice = []
	Bob = []
	Both = []
	none = []
	z = 1
	while n:
		i = sys.stdin.readline().split()
		x = 3
		i.append(z)
		while x:
			i[x - 1] = int(i[x - 1])
			x -= 1
		all.append(i)
		if i[1] == i[2]:
			if i[1] == 0:
				none.append(i)
			else:
				Both.append(i)
		elif i[1] == 0:
			Bob.append(i)
		else:
			Alice.append(i)
		z += 1
		n -= 1
	Alice.sort(key=lambda x: x[0])
	Bob.sort(key=lambda x: x[0])
	Both.sort(key=lambda x: x[0])
	none.sort(key=lambda x: x[0])
	tresult = []
	if 2 * k > m:
		l = 2 * k - m
		if len(Both) >= l:
			tresult = Both[:l]
			Both = Both[l:]
			All = Alice + Both + Bob + none
			m = 2 * (m - k)
			k = k - l
		else:
			print(-1)
			exit()
	else:
		tresult = []
	tresult1 = []
	if min(len(Alice), len(Bob)) == len(Alice):
		if len(Alice) < k:
			k1 = k - len(Alice)
			if len(Both) < k1:
				print(-1)
				exit()
			else:
				tresult1 = Both[:k1]
				Both = Both[k1:]
				k = k - k1
	elif len(Bob) < k:
		k1 = k - len(Bob)
		if len(Both) < k1:
			print(-1)
			exit()
		else:
			tresult1 = Both[:k1]
			Both = Both[k1:]
			k = k - k1
	Alice1 = Alice[:k]
	Bob1 = Bob[:k]
	Alice = Alice[k:]
	Bob = Bob[k:]
	corr = []
	elev = False
	zz = 0
	while len(Alice1) > 0 and len(Bob1) > 0 and (len(Both) > 0) and (len(none) > 0) and (Alice1[-1][0] + Bob1[-1][0] > Both[0][0] + min(Alice1[-1][0], Bob1[-1][0], none[zz][0])):
		if min(Alice1[-1][0], Bob1[-1][0], none[zz][0]) == none[zz][0]:
			zz += 1
		Alice.append(Alice1[-1])
		Bob.append(Bob1[-1])
		corr.append(Both[0])
		Alice1.pop(-1)
		Bob1.pop(-1)
		Both.pop(0)
	q = len(tresult1) + len(corr) + len(Alice1) + len(Bob1)
	q = m - q
	All = Alice + Bob + Both + none
	All.sort(key=lambda x: x[0])
	result2 = tresult + tresult1 + corr + Alice1 + Bob1
	result = All[:q]
	result = result + tresult + tresult1 + corr + Alice1 + Bob1
	sum1 = 0
	for row in result:
		sum1 = sum1 + row[0]
	print(sum1)
	if sum1 == 0:
		print(sum((row[1] for row in result2)))
		print(sum((row[2] for row in result2)))
		result.sort(key=lambda x: x[0])
		print(result[-1])
		print(result[-2])
		chk = result[-1][0] - 1
		for row in All:
			if row[0] == chk:
				print(row)
	if sum1 == 82207:
		print(len(corr))
		print(corr[-1])
		corr.sort(key=lambda x: x[0])
		print(corr[-1])
		Both.sort(key=lambda x: x[0])
		print(Both[0])
		print(All[q])
	if sum1 == 82207:
		print(all[15429])
		print(all[11655])
	result.sort(key=lambda x: x[3])
	print(' '.join([str(row[3]) for row in result]))
else:
	iva = [[] for _ in range(4)]
	alv = [() for _ in range(n)]
	for i in range(n):
		(v, o, u) = [int(x) for x in input().split()]
		q = o << 1 | u
		iva[q].append((v, i))
		alv[i] = (v, i)
	for e in iva:
		e.sort()
	alv.sort()
	(ct, a, r, ps, an) = (0, 0, 0, min(len(iva[1]), len(iva[2])), 0)
	ana = [False] * n
	for _ in range(k):
		if a < ps and r < len(iva[3]):
			if iva[1][a][0] + iva[2][a][0] < iva[3][r][0]:
				cta(1, a, 1)
				cta(2, a, 1)
				ct += 2
				a += 1
			else:
				cta(3, r, 1)
				ct += 1
				r += 1
		elif a < ps:
			cta(1, a, 1)
			cta(2, a, 1)
			ct += 2
			a += 1
		elif r < len(iva[3]):
			cta(3, r, 1)
			ct += 1
			r += 1
		else:
			print(-1)
			exit(0)
	while ct > m and a > 0 and (r < len(iva[3])):
		a -= 1
		cta(1, a, -1)
		cta(2, a, -1)
		cta(3, r, 1)
		ct -= 1
		r += 1
	ap = 0
	while ct < m and ap < n:
		if not ana[alv[ap][1]]:
			if r > 0 and a < ps and (iva[1][a][0] + iva[2][a][0] - iva[3][r - 1][0] < alv[ap][0]):
				if ana[iva[1][a][1]] or ana[iva[2][a][1]]:
					a += 1
					continue
				r -= 1
				cta(1, a, 1)
				cta(2, a, 1)
				cta(3, r, -1)
				a += 1
				ct += 1
			else:
				ct += 1
				an += alv[ap][0]
				ana[alv[ap][1]] = True
				ap += 1
		else:
			ap += 1
	if ct != m:
		print(-1)
	else:
		print(an)
		for i in range(n):
			if ana[i]:
				print(i + 1, end=' ')


import sys
import collections
import heapq

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def main(hashtable, k):
	alice = bob = 0
	total = 0
	while alice < k or bob < k:
		if alice < k and bob < k:
			if hashtable[1, 1] and hashtable[0, 1] and hashtable[1, 0]:
				if hashtable[1, 1][0] < hashtable[0, 1][0] + hashtable[1, 0][0]:
					total += heapq.heappop(hashtable[1, 1])
					alice += 1
					bob += 1
				else:
					total += heapq.heappop(hashtable[0, 1])
					total += heapq.heappop(hashtable[1, 0])
					alice += 1
					bob += 1
			elif hashtable[1, 1]:
				total += heapq.heappop(hashtable[1, 1])
				alice += 1
				bob += 1
			elif hashtable[0, 1] and hashtable[1, 0]:
				total += heapq.heappop(hashtable[0, 1])
				total += heapq.heappop(hashtable[1, 0])
				alice += 1
				bob += 1
			else:
				print(-1)
				return -1
	print(total)
	return total
(N, k) = get_ints()
hashtable = collections.defaultdict(list)
for i in range(N):
	(t, a, b) = get_ints()
	heapq.heappush(hashtable[a, b], t)
main(hashtable, k)


(book, k) = map(int, input().split())
(both, bob, alice) = (dict(), dict(), dict())
for i in range(book):
	(time, x, y) = map(int, input().split())
	if x == 1 and y == 0:
		alice[i] = time
	elif x == 0 and y == 1:
		bob[i] = time
	elif x == 1 and y == 1:
		both[i] = time
if len(both) + len(alice) < k or len(both) + len(bob) < k:
	print(-1)
	exit()
else:
	alice = sorted(alice.items(), key=lambda x: x[1])
	bob = sorted(bob.items(), key=lambda x: x[1])
	both = sorted(both.items(), key=lambda x: x[1])
	(count, x, y, z, time) = (0, 0, 0, 0, 0)
	while count < k:
		if x < len(alice) and y < len(bob) and (z < len(both)):
			if alice[x][1] + bob[y][1] < both[z][1]:
				time += alice[x][1] + bob[y][1]
				x += 1
				y += 1
				count += 1
			else:
				time += both[z][1]
				count += 1
				z += 1
		elif z >= len(both):
			time += alice[x][1] + bob[y][1]
			x += 1
			y += 1
			count += 1
		else:
			time += both[z][1]
			count += 1
			z += 1
	print(time)


import bisect
import sys
import math
input = sys.stdin.readline
import functools
import heapq
from collections import defaultdict

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())

def solve():
	[n, k] = inlt()
	bks = []
	for i in range(n):
		[t, a, b] = inlt()
		bks.append((t, a, b))
	bks.sort(key=lambda x: x[0])
	aa = [v for v in bks if v[1] == 1 and v[2] == 0][:k]
	bb = [v for v in bks if v[1] == 0 and v[2] == 1][:k]
	com = [v for v in bks if v[1] == 1 and v[2] == 1][:k]
	com_picked = []
	for b in com:
		acount = len(aa) + len(com_picked)
		bcount = len(bb) + len(com_picked)
		if acount < k or bcount < k or b[0] < aa[-1][0] + bb[-1][0]:
			com_picked.append(b)
			if acount >= k:
				aa.pop()
			if bcount >= k:
				bb.pop()
	acount = len(aa) + len(com_picked)
	bcount = len(bb) + len(com_picked)
	if acount < k or bcount < k:
		return -1
	res = 0
	res += sum((t for (t, _, _) in aa))
	res += sum((t for (t, _, _) in bb))
	res += sum((t for (t, _, _) in com_picked))
	return res
if len(sys.argv) > 1 and sys.argv[1].startswith('input'):
	f = open('./' + sys.argv[1], 'r')
	input = f.readline
res = solve()
print(str(res))


from collections import deque
import sys

def inp():
	return sys.stdin.readline().strip()
for _ in range(1):
	(n, k) = map(int, inp().split())
	l = []
	a = []
	b = []
	for i in range(n):
		(ti, ai, bi) = map(int, inp().split())
		if ai == 0 and bi == 0:
			continue
		elif ai == 0:
			b.append(ti)
		elif bi == 0:
			a.append(ti)
		else:
			l.append(ti)
	if len(a) + len(l) < k or len(b) + len(l) < k:
		print(-1)
		continue
	a.sort()
	b.sort()
	l.sort()
	p1 = p2 = p3 = 0
	req = min(max(k - len(a), 0) + max(k - (len(b) + max(k - len(a), 0)), 0), len(l))
	ra = rb = req
	p3 = req
	t = sum(l[:req])
	while ra < k or rb < k:
		if p3 == len(l):
			if ra < k:
				ra += 1
				t += a[p1]
				p1 += 1
			if rb < k:
				rb += 1
				t += b[p2]
				p2 += 1
			continue
		elif ra == k:
			rb += 1
			if p2 == len(b) and p1 - 1 >= 0 and (p1 - 1 < len(a)) or (p1 - 1 >= 0 and p1 - 1 < len(a) and (l[p3] < b[p2] + a[p1 - 1])):
				t += l[p3] - a[p1 - 1]
				p3 += 1
				p1 -= 1
			elif p2 == len(b) or l[p3] < b[p2]:
				t += l[p3]
				p3 += 1
			else:
				t += b[p2]
				p2 += 1
		elif rb == k:
			ra += 1
			if p1 == len(a) and p2 - 1 >= 0 and (p2 - 1 < len(b)) or (p2 - 1 >= 0 and p2 - 1 < len(b) and (l[p3] < b[p2 - 1] + a[p1])):
				t += l[p3] - b[p2 - 1]
				p3 += 1
				p2 -= 1
			elif p1 == len(a) or l[p3] < a[p1]:
				t += l[p3]
				p3 += 1
			else:
				t += a[p1]
				p1 += 1
		elif p1 == len(a) or p2 == len(b) or l[p3] < a[p1] + b[p2]:
			t += l[p3]
			p3 += 1
			if ra < k:
				ra += 1
			if rb < k:
				rb += 1
		else:
			ra += 1
			rb += 1
			t += a[p1]
			t += b[p2]
			p1 += 1
			p2 += 1
	print(t)


(n, k) = map(int, input().split())
(a, b, t) = ([], [], [])
for i in range(0, n):
	(tm, c, d) = map(int, input().split())
	if c == 1 and d == 1:
		t.append(tm)
	elif c == 1 and d == 0:
		a.append(tm)
	elif c == 0 and d == 1:
		b.append(tm)
if len(t) + len(a) < k or len(t) + len(b) < k:
	print(-1)
else:
	t.sort()
	a.sort()
	b.sort()
	i = 0
	j = 0
	ans = 0
	fga = 0
	fgt = 0
	while k != 0:
		if len(a) <= j or len(b) <= j:
			fga = 1
			break
		elif len(t) <= i:
			fgt = 1
			break
		elif t[i] > a[j] + b[j]:
			ans += a[j] + b[j]
			j += 1
		elif t[i] <= a[j] + b[j]:
			ans += t[i]
			i += 1
		k -= 1
	if fga == 1 and fgt == 0:
		while k != 0:
			ans += t[i]
			i += 1
			k -= 1
	elif fga == 0 and fgt != 0:
		while k != 0:
			ans += a[j] + b[j]
			j += 1
			k -= 1
	print(ans)


from sys import stdin
input = stdin.readline
(n, k) = map(int, input().split())
al = []
bl = []
abl = []
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a and b:
		abl.append(t)
	elif a:
		al.append(t)
	elif b:
		bl.append(t)
al.sort()
bl.sort()
abl.sort()
sl = list(map(lambda o: o[0] + o[1], zip(al, bl)))
abl.reverse()
sl.reverse()
c = 0
while abl and sl and k:
	if abl[-1] < sl[-1]:
		c += abl.pop()
	else:
		c += sl.pop()
	k -= 1
if k:
	if len(abl) + len(sl) < k:
		print(-1)
	else:
		while k:
			if abl:
				c += abl.pop()
			else:
				c += sl.pop()
			k -= 1
		print(c)
else:
	print(c)


line = input()
(n, k) = [int(i) for i in line.split(' ')]
(allL, aliceL, bobL) = ([], [], [])
for i in range(n):
	line = input()
	(t, a, b) = [int(j) for j in line.split(' ')]
	if a == 1 and b == 1:
		allL.append(t)
	elif a == 1:
		aliceL.append(t)
	elif b == 1:
		bobL.append(t)
allL.sort()
aliceL.sort()
bobL.sort()
if len(allL) + min(len(aliceL), len(bobL)) < k:
	print(-1)
else:
	x = min(len(allL), k)
	b = k - x
	res = sum(allL[:x]) + sum(aliceL[:b]) + sum(bobL[:b])
	while x > 0 and b < min(len(aliceL), len(bobL)):
		x -= 1
		if res <= res - allL[x] + aliceL[b] + bobL[b]:
			break
		else:
			res = res - allL[x] + aliceL[b] + bobL[b]
		b += 1
	print(res)


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
BOOKS = [tuple(map(int, input().split())) for i in range(n)]
A = []
B = []
AB = []
for (t, a, b) in BOOKS:
	if a == 1 and b == 1:
		AB.append(t)
	if a == 1 and b == 0:
		A.append(t)
	if a == 0 and b == 1:
		B.append(t)
A.sort()
B.sort()
AB.sort()
from itertools import accumulate
SA = [0] + list(accumulate(A))
SB = [0] + list(accumulate(B))
SAB = [0] + list(accumulate(AB))
ANS = 1 << 31
for i in range(len(SAB)):
	if 0 <= k - i < len(SA) and 0 <= k - i < len(SB):
		ANS = min(ANS, SAB[i] + SA[k - i] + SB[k - i])
if ANS == 1 << 31:
	print(-1)
else:
	print(ANS)


(n, k) = map(int, input().split())
a = []
b = []
anb = []
for i in range(n):
	(x, y, z) = map(int, input().split())
	if y == 0 and z == 1:
		b.append(x)
	elif y == 1 and z == 0:
		a.append(x)
	elif y == 1 and z == 1:
		anb.append(x)
a.sort()
b.sort()
if len(a) < len(b):
	b = b[:len(a)]
else:
	a = a[:len(b)]
for i in range(len(a)):
	a[i] += b[i]
anb += a
anb.sort()
ans = 0
if len(anb) < k:
	print(-1)
else:
	print(sum(anb[:k]))


(n, k) = map(int, input().split())
(a, m, b) = ([], [], [])
for i in range(n):
	(ti, ai, bi) = map(int, input().split())
	if ai == 1 and bi == 1:
		m.append(ti)
	elif ai == 1:
		a.append(ti)
	elif bi == 1:
		b.append(ti)
a.sort()
m.sort()
b.sort()
pm = [0] * (len(m) + 1)
for i in range(1, len(m) + 1):
	pm[i] = pm[i - 1] + m[i - 1]
pa = [0] * (len(a) + 1)
for i in range(1, len(a) + 1):
	pa[i] = pa[i - 1] + a[i - 1]
pb = [0] * (len(b) + 1)
for i in range(1, len(b) + 1):
	pb[i] = pb[i - 1] + b[i - 1]
ans = 10 ** 12
for c in range(min(k + 1, len(m) + 1)):
	if min(len(a), len(b)) >= k - c and ans > pm[c] + pa[k - c] + pb[k - c]:
		ans = pm[c] + pa[k - c] + pb[k - c]
if ans == 10 ** 12:
	print(-1)
else:
	print(ans)


(n, k) = input().split()
n = int(n)
k = int(k)
c = []
a = []
b = []
for i in range(n):
	(t, al, bo) = input().split()
	if al == '1' and bo == '1':
		c.append(int(t))
	elif al == '1':
		a.append(int(t))
	elif bo == '1':
		b.append(int(t))
if len(c) + len(a) < k or len(c) + len(b) < k:
	print(-1)
	quit()
c.sort()
a.sort()
b.sort()
for i in range(1, len(c)):
	c[i] = c[i] + c[i - 1]
for i in range(1, len(a)):
	a[i] = a[i] + a[i - 1]
for i in range(1, len(b)):
	b[i] = b[i] + b[i - 1]
high = 2147483640
p = 0
tempo = 0
while p <= len(c) and p <= k:
	if p > 0:
		tempo = c[p - 1]
	else:
		tempo = 0
	dif = k - p
	if len(a) >= dif and len(b) >= dif:
		if dif > 0:
			tempo = tempo + (a[dif - 1] + b[dif - 1])
		if high >= tempo:
			high = tempo
	p = p + 1
print(high)


from collections import deque
(n, k) = map(int, input().split())
onla = []
onlb = []
both = []
for i in range(n):
	(a, b, c) = map(int, input().split())
	if b == 1 and c == 1:
		both.append(a)
	elif c == 1:
		onlb.append(a)
	elif b == 1:
		onla.append(a)
if len(both) + len(onla) < k or len(both) + len(onlb) < k:
	print(-1)
else:
	onlb.sort()
	onlb = deque(onlb)
	onla.sort()
	onla = deque(onla)
	both.sort()
	both = deque(both)
	al = k
	bob = k
	ans = 0
	while al > 0 or bob > 0:
		if al > 0 and bob > 0:
			if len(onla) == 0 or len(onlb) == 0:
				ans += both[0]
				al -= 1
				bob -= 1
				both.popleft()
			elif len(both) == 0:
				ans += onla[0] + onlb[0]
				al -= 1
				bob -= 1
				onla.popleft()
				onlb.popleft()
			elif onla[0] + onlb[0] <= both[0]:
				ans += onla[0] + onlb[0]
				al -= 1
				bob -= 1
				onla.popleft()
				onlb.popleft()
			else:
				ans += both[0]
				al -= 1
				bob -= 1
				both.popleft()
		elif bob > 0:
			if both[0] < onlb[0]:
				ans += both[0]
				bob -= 1
				both.popleft()
			else:
				ans += onlb[0]
				bob -= 1
				onlb.popleft()
		elif al > 0:
			if both[0] < onla[0]:
				ans += both[0]
				bob -= 1
				both.popleft()
			else:
				ans += onla[0]
				bob -= 1
				onlb.popleft()
	print(ans)


(n, k) = map(int, input().split(' '))
arr_a = []
arr_b = []
arr_c = []
cnt1 = 0
cnt2 = 0
for i in range(0, n):
	(t, a, b) = map(int, input().split(' '))
	if a == 1 and b == 1:
		cnt1 += 1
		cnt2 += 1
		arr_c.append(t)
	elif a == 1 and b == 0:
		cnt1 += 1
		arr_a.append(t)
	elif a == 0 and b == 1:
		cnt2 += 1
		arr_b.append(t)
if cnt1 < k or cnt2 < k:
	print(-1)
else:
	arr_a.sort()
	arr_b.sort()
	arr_c.sort()
	cnt = 0
	ans = 0
	x = 0
	y = 0
	z = 0
	while cnt < k:
		if x >= len(arr_c):
			cnt += 1
			ans += arr_a[y] + arr_b[z]
			y += 1
			z += 1
		elif y >= len(arr_a) or z >= len(arr_b):
			cnt += 1
			ans += arr_c[x]
			x += 1
		elif arr_c[x] < arr_a[y] + arr_b[z]:
			cnt += 1
			ans += arr_c[x]
			x += 1
		else:
			cnt += 1
			ans += arr_a[y] + arr_b[z]
			y += 1
			z += 1
	print(ans)


(n, k) = map(int, input().split())
ablike = []
alike = []
blike = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		ablike.append(t)
	elif a == 1:
		alike.append(t)
	elif b == 1:
		blike.append(t)
ablike.sort()
abtot = len(ablike)
alike.sort()
atot = len(alike)
blike.sort()
btot = len(blike)
x = min(atot, btot)
if abtot + x < k:
	print(-1)
else:
	p = k
	i = 0
	j = 0
	tot = 0
	while p > 0:
		if j < abtot and i < x:
			if ablike[j] <= alike[i] + blike[i]:
				tot = tot + ablike[j]
				j = j + 1
				p = p - 1
			else:
				tot = tot + alike[i] + blike[i]
				i = i + 1
				p = p - 1
		elif j < abtot:
			tot = tot + ablike[j]
			j = j + 1
			p = p - 1
		else:
			tot = tot + alike[i] + blike[i]
			i = i + 1
			p = p - 1
	print(tot)


(n, k) = list(map(int, input().split()))
a = []
b = []
ab = []
for _ in range(0, n):
	(t, x, y) = list(map(int, input().split()))
	if x == 1 and y == 1:
		ab.append(t)
	elif x == 1:
		a.append(t)
	elif y == 1:
		b.append(t)
ab.sort(reverse=True)
b.sort(reverse=True)
a.sort(reverse=True)
ca = 0
cb = 0
t = 0
c = 0
u = 0
while len(a) != 0 and len(b) != 0:
	if len(ab) > 0 and ab[-1] <= a[-1] + b[-1]:
		t += ab.pop()
		c += 1
	else:
		t = t + a.pop() + b.pop()
		c += 1
	if c == k:
		u = 1
		break
if u == 1:
	print(t)
elif c + len(ab) < k:
	print(-1)
else:
	t += sum(ab[-(k - c):])
	print(t)


(n, k) = map(int, input().split())
alice = []
bob = []
both = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
alice.sort()
bob.sort()
l = min(len(alice), len(bob))
for i in range(l):
	both.append(alice[i] + bob[i])
if len(both) < k:
	print(-1)
else:
	both.sort()
	sumi = 0
	for i in range(k):
		sumi = sumi + both[i]
	print(sumi)


lis = input().split()
(n, k) = (int(lis[0]), int(lis[1]))
like1 = []
like2 = []
likeall = []
for i in range(n):
	lis = input().split()
	(tval, l1, l2) = (int(lis[0]), int(lis[1]), int(lis[2]))
	if l1 == 1 and l2 == 1:
		likeall.append(tval)
	elif l1 == 1:
		like1.append(tval)
	elif l2 == 1:
		like2.append(tval)
like1.sort()
like2.sort()
likeall.sort()
if len(like1) < len(like2):
	mm = len(like1)
	like2 = like2[:len(like1)]
elif len(like1) > len(like2):
	mm = len(like2)
	like1 = like1[:len(like2)]
else:
	mm = len(like1)
if mm + len(likeall) < k:
	print(-1)
else:
	likedouble = [0] * mm
	for i in range(mm):
		likedouble[i] = like1[i] + like2[i]
	merged = [0] * (mm + len(likeall))
	(ind, ind1, ind2) = (0, 0, 0)
	while ind < k and ind1 < mm and (ind2 < len(likeall)):
		if likedouble[ind1] < likeall[ind2]:
			merged[ind] = likedouble[ind1]
			ind += 1
			ind1 += 1
		else:
			merged[ind] = likeall[ind2]
			ind += 1
			ind2 += 1
	while ind < k and ind1 < mm:
		merged[ind] = likedouble[ind1]
		ind += 1
		ind1 += 1
	while ind < k and ind2 < len(likeall):
		merged[ind] = likeall[ind2]
		ind += 1
		ind2 += 1
	sum = 0
	for i in range(k):
		sum += merged[i]
	print(sum)


(n, k) = list(map(int, input().split()))
(a11, a10, a01) = ([], [], [])
(c, d) = (0, 0)
for i in range(n):
	(t, a, b) = list(map(int, input().split()))
	if a == 1 and b == 1:
		a11.append(t)
	elif a == 1 and b == 0:
		a10.append(t)
	elif a == 0 and b == 1:
		a01.append(t)
	c += a
	d += b
a11.sort()
a10.sort()
a01.sort()
if c >= k and d >= k:
	(ans, f) = (0, 0)
	(p1, p2, p3) = (0, 0, 0)
	s1 = 10 ** 10
	s2 = 10 ** 10
	if len(a11) >= k:
		po = sum(a11[:k])
		s1 = min(s1, po)
	if len(a10) >= k and len(a01) >= k:
		(v1, v2) = (sum(a10[:k]), sum(a01[:k]))
		s2 = min(s2, v1 + v2)
	for i in range(k):
		if p2 < len(a10) and p3 < len(a01):
			if p1 < len(a11):
				x = a10[p2]
				y = a01[p3]
				z = a11[p1]
				if z < x + y:
					p1 += 1
				else:
					p2 += 1
					p3 += 1
				ans += min(x + y, z)
			else:
				x = a10[p2]
				y = a01[p3]
				ans += x + y
				p2 += 1
				p3 += 1
		elif p1 < len(a11):
			ans += a11[p1]
			p1 += 1
		else:
			f = 1
			break
	if f == 1:
		print(-1)
	else:
		print(min(ans, s1, s2))
else:
	print(-1)


(n, k) = [int(x) for x in input().split()]
bookA = []
bookB = []
bookC = []
for i in range(n):
	(a, b, c) = [int(x) for x in input().split()]
	if b == c == 1:
		bookC.append((a, b, c))
	if b == 1 != c:
		bookA.append((a, b, c))
	if c == 1 != b:
		bookB.append((a, b, c))
bookA.sort(key=lambda x: x[0], reverse=True)
bookB.sort(key=lambda x: x[0], reverse=True)
bookC.sort(key=lambda x: x[0], reverse=True)
totalTime = 0
totalLikes = 0
while True:
	if totalLikes >= k:
		break
	if len(bookA) == len(bookC) == len(bookB) == 0:
		break
	elif len(bookC) > 0 and (len(bookA) == 0 or len(bookB) == 0 or bookC[len(bookC) - 1][0] <= bookA[len(bookA) - 1][0] + bookB[len(bookB) - 1][0]):
		totalTime += bookC[len(bookC) - 1][0]
		bookC.pop()
		totalLikes += 1
	elif len(bookA) > 0 and len(bookB) > 0:
		totalTime += bookA[len(bookA) - 1][0] + bookB[len(bookB) - 1][0]
		totalLikes += 1
		bookA.pop()
		bookB.pop()
	else:
		break
if totalLikes >= k:
	print(totalTime)
else:
	print(-1)


from sys import stdin, stdout
import heapq as hq
from collections import defaultdict
t = 1
for tc in range(t):
	(n, k) = list(map(int, stdin.readline().split()))
	lib = []
	for nc in range(n):
		lib.append(tuple(map(int, stdin.readline().split())))
	libA = []
	libB = []
	libAB = []
	for book in lib:
		if book[1] + book[2] == 2:
			libAB.append(book)
		elif book[1] == 1:
			libA.append(book)
		elif book[2] == 1:
			libB.append(book)
	libA = sorted(libA, key=lambda x: x[0])
	libB = sorted(libB, key=lambda x: x[0])
	libAB = sorted(libAB, key=lambda x: x[0])
	res = 0
	p1 = 0
	p2 = 0
	while k > 0 and p1 < len(libA) and (p1 < len(libB)) and (p2 < len(libAB)):
		if libA[p1][0] + libB[p1][0] < libAB[p2][0]:
			res += libA[p1][0] + libB[p1][0]
			p1 += 1
			k -= 1
		else:
			res += libAB[p2][0]
			p2 += 1
			k -= 1
	while k > 0 and p2 < len(libAB):
		res += libAB[p2][0]
		p2 += 1
		k -= 1
	while k > 0 and p1 < len(libA) and (p1 < len(libB)):
		res += libA[p1][0] + libB[p1][0]
		p1 += 1
		k -= 1
	if k > 0:
		res = -1
	stdout.write(str(res))


import bisect
import sys
import math
input = sys.stdin.readline
import functools
import heapq
from collections import defaultdict

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())

def solve():
	[n, m, k] = inlt()
	bks = []
	for i in range(n):
		[t, a, b] = inlt()
		bks.append((t, a, b, i + 1))
	bks.sort(key=lambda x: x[0])
	aa_i = [v for v in bks if v[1] == 1 and v[2] == 0]
	bb_i = [v for v in bks if v[1] == 0 and v[2] == 1]
	cc_i = [v for v in bks if v[1] == 1 and v[2] == 1]
	dd_i = [v for v in bks if v[1] == 0 and v[2] == 0]
	aa = [0]
	bb = [0]
	cc = [0]
	dd = [0]
	for v in bks:
		if v[1] == 1 and v[2] == 0:
			aa.append(aa[-1] + v[0])
		if v[1] == 0 and v[2] == 1:
			bb.append(bb[-1] + v[0])
		if v[1] == 1 and v[2] == 1:
			cc.append(cc[-1] + v[0])
		if v[1] == 0 and v[2] == 0:
			dd.append(dd[-1] + v[0])
	take_a = min(len(aa) - 1, k)
	take_b = min(len(bb) - 1, k)
	take_c = 0
	take_d = 0
	while True:
		if take_c >= len(cc) - 1:
			break
		picked = take_a + take_b + take_c + take_d
		if take_a + take_c < k or take_b + take_c < k:
			take_c += 1
		elif take_a > 0 and take_b > 0 and (picked > m):
			take_c += 1
		elif take_a > 0 and take_b > 0 and (aa[take_a - 1] + bb[take_b - 1] + cc[take_c + 1] < aa[take_a] + bb[take_b] + cc[take_c]):
			take_c += 1
		else:
			break
		while take_a + take_c > k and take_a > 0:
			take_a -= 1
		while take_b + take_c > k and take_b > 0:
			take_b -= 1
	if take_a + take_c < k or take_b + take_c < k or take_a + take_b + take_c + take_d > m:
		print(-1)
		return
	while take_a + take_b + take_c + take_d < m:
		cases = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [1, 1, -1, 0]]
		cases = [[take_a + case[0], take_b + case[1], take_c + case[2], take_d + case[3]] for case in cases]
		flag = False
		for (i, case) in enumerate(cases):
			new_take_a = case[0]
			new_take_b = case[1]
			new_take_c = case[2]
			new_take_d = case[3]
			if new_take_a < 0 or new_take_a >= len(aa):
				continue
			if new_take_b < 0 or new_take_b >= len(bb):
				continue
			if new_take_c < 0 or new_take_c >= len(cc):
				continue
			if new_take_d < 0 or new_take_d >= len(dd):
				continue
			if not flag or aa[new_take_a] + bb[new_take_b] + cc[new_take_c] + dd[new_take_d] < aa[take_a] + bb[take_b] + cc[take_c] + dd[take_d]:
				(take_a, take_b, take_c, take_d) = (new_take_a, new_take_b, new_take_c, new_take_d)
				flag = True
	res = aa[take_a] + bb[take_b] + cc[take_c] + dd[take_d]
	res_arr = []
	for i in range(take_a):
		res_arr.append(aa_i[i][3])
	for i in range(take_b):
		res_arr.append(bb_i[i][3])
	for i in range(take_c):
		res_arr.append(cc_i[i][3])
	for i in range(take_d):
		res_arr.append(dd_i[i][3])
	res_arr.sort()
	res_arr = [str(v) for v in res_arr]
	print(res)
	print(' '.join(res_arr))
	return res
if len(sys.argv) > 1 and sys.argv[1].startswith('input'):
	f = open('./' + sys.argv[1], 'r')
	input = f.readline
res = solve()


(n, k) = map(int, input().split())
aa = []
bb = []
l = []
for _ in range(n):
	(t, a, b) = map(int, input().split())
	sum1 = 0
	sum2 = 0
	if a & b:
		l.append(t)
	elif a == 1:
		aa.append(t)
	elif b == 1:
		bb.append(t)
bb.sort()
aa.sort()
nn = min(len(aa), len(bb))
for i in range(nn):
	l.append(bb[i] + aa[i])
if k > len(l):
	print(-1)
else:
	l.sort()
	sum1 = 0
	for i in range(k):
		sum1 += l[i]
	print(sum1)


import sys
from operator import add
t = 1

def inp():
	return sys.stdin.readline().strip()
for _ in range(t):
	(n, k) = map(int, inp().split())
	bothbooks = []
	abooks = []
	bbooks = []
	for i in range(n):
		(t, a, b) = map(int, inp().split())
		if a == 1 and b == 1:
			bothbooks.append(t)
		elif a == 1 and b == 0:
			abooks.append(t)
		elif a == 0 and b == 1:
			bbooks.append(t)
	abooks.sort()
	bbooks.sort()
	abbooks = [a + b for (a, b) in zip(abooks, bbooks)]
	abbooks = abbooks + bothbooks
	abbooks.sort()
	if k > len(abbooks):
		print(-1)
	else:
		print(sum(abbooks[0:k]))


(n, k) = map(int, input().split())
l = []
ll = []
lll = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		l.append(t)
	elif a == 1:
		ll.append(t)
	elif b == 1:
		lll.append(t)
ll.sort()
lll.sort()
for i in range(min(len(ll), len(lll))):
	l.append(ll[i] + lll[i])
we = len(l)
if k > we:
	print(-1)
else:
	l.sort()
	ans = 0
	for i in range(k):
		ans += l[i]
	print(ans)


(n, k) = map(int, input().split())
arr = [[int(i) for i in input().split()] for _ in range(n)]
a = sorted([arr[i][0] for i in range(n) if arr[i][1] == 1 and arr[i][2] == 0])
b = sorted([arr[i][0] for i in range(n) if arr[i][1] == 0 and arr[i][2] == 1])
ab = sorted([arr[i][0] for i in range(n) if arr[i][1] == 1 and arr[i][2] == 1])
ans = 0
(l, r) = (0, 0)
for i in range(k):
	v1 = 10 ** 9
	if len(a) > l and len(b) > l:
		v1 = a[l] + b[l]
	v2 = 10 ** 9
	if len(ab) > r:
		v2 = ab[r]
	if v1 == v2 == 10 ** 9:
		ans = -1
		break
	if v1 < v2:
		l += 1
		ans += v1
	else:
		r += 1
		ans += v2
print(ans)


(n, k) = map(int, input().split())
alice = []
bob = []
common = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a and b:
		common.append(t)
	elif a:
		alice.append(t)
	elif b:
		bob.append(t)
alice.sort()
bob.sort()
for i in range(min(len(alice), len(bob))):
	common.append(alice[i] + bob[i])
if len(common) < k:
	print(-1)
else:
	common.sort()
	print(sum(common[:k]))


import sys
import bisect as b
import math
from collections import defaultdict as dd
input = sys.stdin.readline

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())
for _ in range(1):
	(n, k) = cin()
	l = []
	l1 = []
	l3 = []
	for i in range(n):
		(t, a, b) = cin()
		if a == 1 and b == 1:
			l3 += [t]
		elif a == 1:
			l += [t]
		elif b == 1:
			l1 += [t]
	l = sorted(l, reverse=True)
	l1 = sorted(l1, reverse=True)
	l3 = sorted(l3, reverse=True)
	ans = -1
	ma = 10 ** 5
	if len(l) + len(l3) >= k and len(l1) + len(l3) >= k:
		ans = 0
		k1 = k2 = k
		while k1 > 0 and k2 > 0:
			if len(l1) == 0:
				l1 += [ma]
			if len(l) == 0:
				l += [ma]
			if len(l3) == 0:
				l3 += [ma]
			if l[-1] + l1[-1] > l3[-1]:
				ans += l3.pop()
			else:
				ans += l1.pop()
				ans += l.pop()
			k1 -= 1
			k2 -= 1
	print(ans)


(n, k) = [int(s) for s in input().split(' ')]
alice = []
bob = []
both = []
for i in range(n):
	(t, a, b) = list(map(int, input().split(' ')))
	if a == b == 1:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
	else:
		continue
alice.sort()
bob.sort()
for i in range(min(len(alice), len(bob))):
	both.append(alice[i] + bob[i])
both.sort()
if k > len(both):
	print(-1)
else:
	print(sum(both[:k]))


(n, k) = map(int, input().split())
Books = []
(Alice, Bob, Common_Books) = ([], [], [])
for i in range(n):
	Book = tuple(map(int, input().split()))
	Books.append(Book)
Books = sorted(Books, key=lambda x: x[0])
for Book in Books:
	if Book[1] == 1 and Book[2] == 1:
		if len(Common_Books) < k:
			Common_Books.append(Book)
		else:
			break
	else:
		if len(Alice) != k and Book[1] == 1:
			Alice.append(Book)
		if len(Bob) != k and Book[2] == 1:
			Bob.append(Book)
t = len(Common_Books)
if len(Alice) < k - t or len(Bob) < k - t:
	print(-1)
else:
	Min_time = 0
	(a, iab, ic) = (0, 0, 0)
	while a < k:
		if iab < len(Alice):
			A = Alice[iab]
		else:
			A = (float('inf'), 0, 0)
		if iab < len(Bob):
			B = Bob[iab]
		else:
			B = (float('inf'), 0, 0)
		if ic < len(Common_Books):
			C = Common_Books[ic]
		else:
			C = (float('inf'), 0, 0)
		if A[0] + B[0] < C[0]:
			Min_time += A[0] + B[0]
			iab += 1
		else:
			Min_time += C[0]
			ic += 1
		a += 1
	print(Min_time)


(n, k) = map(int, input().split())
(A, B, C) = ([], [], [])
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x == 1 and y == 1:
		C.append(t)
		continue
	if x == 1:
		A.append(t)
		continue
	if y == 1:
		B.append(t)

def fun(l):
	pre = [0]
	for i in l:
		pre.append(pre[-1] + i)
	return pre
A.sort()
B.sort()
C.sort()
a = fun(A)
b = fun(B)
c = fun(C)
if len(A) + len(C) < k or len(B) + len(C) < k:
	print(-1)
else:
	ans = 999999999999999999999999999
	for i in range(min(len(C), k) + 1):
		if k - i < len(a) and k - i < len(b):
			ans = min(ans, c[i] + a[k - i] + b[k - i])
	print(ans)


import sys
s = sys.stdin.readline().split()
(n, m, k) = (int(s[0]), int(s[1]), int(s[2]))
all = []
All = []
Alice = []
Bob = []
Both = []
none = []
z = 1
while n:
	i = sys.stdin.readline().split()
	x = 3
	i.append(z)
	while x:
		i[x - 1] = int(i[x - 1])
		x -= 1
	all.append(i)
	if i[1] == i[2]:
		if i[1] == 0:
			none.append(i)
		else:
			Both.append(i)
	elif i[1] == 0:
		Bob.append(i)
	else:
		Alice.append(i)
	z += 1
	n -= 1
Alice.sort(key=lambda x: x[0])
Bob.sort(key=lambda x: x[0])
Both.sort(key=lambda x: x[0])
none.sort(key=lambda x: x[0])
tresult = []
if 2 * k > m:
	l = 2 * k - m
	if len(Both) >= l:
		tresult = Both[:l]
		Both = Both[l:]
		All = Alice + Both + Bob + none
		m = 2 * (m - k)
		k = k - l
	else:
		print(-1)
		exit()
else:
	tresult = []
tresult1 = []
if min(len(Alice), len(Bob)) == len(Alice):
	if len(Alice) < k:
		k1 = k - len(Alice)
		if len(Both) < k1:
			print(-1)
			exit()
		else:
			tresult1 = Both[:k1]
			Both = Both[k1:]
			k = k - k1
elif len(Bob) < k:
	k1 = k - len(Bob)
	if len(Both) < k1:
		print(-1)
		exit()
	else:
		tresult1 = Both[:k1]
		Both = Both[k1:]
		k = k - k1
Alice1 = Alice[:k]
Bob1 = Bob[:k]
Alice = Alice[k:]
Bob = Bob[k:]
corr = []
calczz = m - 2 * k - len(tresult1)
if calczz > 0:
	xtr = []
	if len(Alice) > calczz:
		xtr = Alice[:calczz]
	else:
		xtr = Alice
	if len(Bob) > calczz:
		xtr = xtr + Bob[:calczz]
	else:
		xtr = xtr + Bob
	if len(none) > calczz:
		xtr = xtr + none[:calczz]
	else:
		xtr = xtr + none
	xtr = xtr[:calczz]
	xtr.sort(key=lambda x: (x[1], x[2]), reverse=True)
	zz = sum((row[1] == row[2] == 0 for row in xtr))
else:
	zz = 0
if len(none) == zz:
	nonechk = 9999999999
else:
	nonechk = none[zz][0]
while len(Alice1) > 0 and len(Bob1) > 0 and (len(Both) > 0) and (len(none) > 0) and (Alice1[-1][0] + Bob1[-1][0] >= Both[0][0] + min(Alice1[-1][0], Bob1[-1][0], nonechk)):
	if min(Alice1[-1][0], Bob1[-1][0], nonechk) == nonechk:
		zz += 1
		if len(none) == zz:
			nonechk = 9999999999
		else:
			nonechk = none[zz][0]
	Alice.append(Alice1[-1])
	Bob.append(Bob1[-1])
	corr.append(Both[0])
	Alice1.pop(-1)
	Bob1.pop(-1)
	Both.pop(0)
q = len(tresult1) + len(corr) + len(Alice1) + len(Bob1)
q = m - q
All = Alice + Bob + Both + none
All.sort(key=lambda x: x[0])
result2 = tresult + tresult1 + corr + Alice1 + Bob1
result = All[:q]
result = result + tresult + tresult1 + corr + Alice1 + Bob1
result.sort(key=lambda x: x[0])
sum1 = 0
for row in result:
	sum1 = sum1 + row[0]
print(sum1)
result.sort(key=lambda x: x[3])
print(' '.join([str(row[3]) for row in result]))


from sys import stdin, setrecursionlimit, stdout
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
from heapq import heapify, heappop, heappush, heappushpop, heapreplace

def ii():
	return int(stdin.readline())

def fi():
	return float(stdin.readline())

def mi():
	return map(int, stdin.readline().split())

def fmi():
	return map(float, stdin.readline().split())

def li():
	return list(mi())

def si():
	return stdin.readline().rstrip()

def lsi():
	return list(si())
res = ['YES', 'NO']
test_case = 1
while test_case:
	test_case -= 1
	(n, k) = mi()
	both = [0]
	al = [0]
	bob = [0]
	for _ in range(n):
		(x, y, z) = mi()
		if y and z:
			both.append(x)
		elif y:
			al.append(x)
		elif z:
			bob.append(x)
	both.sort()
	for i in range(1, len(both)):
		both[i] += both[i - 1]
	al.sort()
	for i in range(1, len(al)):
		al[i] += al[i - 1]
	bob.sort()
	for i in range(1, len(bob)):
		bob[i] += bob[i - 1]
	ans = 1000000000000000000000000000
	for i in range(len(both)):
		if len(al) > k - i and len(bob) > k - i:
			ans = min(ans, both[i] + al[k - i] + bob[k - i])
		if i == k:
			ans = min(ans, both[i])
			break
	print(-1 if ans == 1000000000000000000000000000 else ans)


import sys
input = sys.stdin.buffer.readline
(n, k) = [int(x) for x in input().split()]
books = []
for _ in range(n):
	books.append([int(x) for x in input().split()])
books.sort(key=lambda x: x[0])
aliceBooks = [0]
bobBooks = [0]
bothBooks = [0]
for i in range(n):
	(ti, ai, bi) = books[i]
	if ai == 1 and bi == 0:
		aliceBooks.append(aliceBooks[-1] + ti)
	if ai == 0 and bi == 1:
		bobBooks.append(bobBooks[-1] + ti)
	if ai == 1 and bi == 1:
		bothBooks.append(bothBooks[-1] + ti)
if min(len(aliceBooks) - 1, len(bobBooks) - 1) + len(bothBooks) - 1 < k:
	print(-1)
else:
	minT = 99999999999999999999999999
	for cnt in range(len(bothBooks) - 1, -1, -1):
		if cnt > k:
			continue
		if k - cnt >= min(len(aliceBooks), len(bobBooks)):
			break
		minT = min(minT, bothBooks[cnt] + aliceBooks[k - cnt] + bobBooks[k - cnt])
	print(minT)


(n, k) = map(int, input().split())
(A, B, both) = ([0], [0], [0])
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		both.append(t)
	if a == 1 and b == 0:
		A.append(t)
	if a == 0 and b == 1:
		B.append(t)
A.sort()
B.sort()
both.sort()
if len(A) - 1 + len(both) - 1 < k or len(B) - 1 + len(both) - 1 < k:
	print(-1)
	exit(0)
for i in range(1, len(A)):
	A[i] += A[i - 1]
for i in range(1, len(B)):
	B[i] += B[i - 1]
cur = 0
ans = 10 ** 12 + 10
for ch in range(len(both)):
	cur += both[ch]
	if ch > k:
		break
	if k - ch < len(A) and k - ch < len(B):
		ans = min(ans, A[k - ch] + B[k - ch] + cur)
print(ans)


(n, k) = map(int, input().split())
ba = []
bb = []
bz = []
for n_ in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		bz.append(t)
	if a == 1 and b == 0:
		ba.append(t)
	if a == 0 and b == 1:
		bb.append(t)
if len(ba) + len(bz) < k or len(bb) + len(bz) < k:
	print(-1)
else:
	ba.sort()
	bb.sort()
	i = 0
	while len(ba) > i and len(bb) > i:
		bz.append(ba[i] + bb[i])
		i += 1
	bz.sort()
	print(sum(bz[:k]))


(n, k) = map(int, input().split())
alice = []
bob = []
both = []
(a, b) = (0, 0)
(al, bl, bol) = (0, 0, 0)
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x == 1 and y == 1:
		both.append(t)
		bol += 1
	elif x == 1:
		alice.append(t)
		al += 1
	elif y == 1:
		bob.append(t)
		bl += 1
alice.sort()
bob.sort()
both.sort()
(ai, bi, boi) = (0, 0, 0)
count = 0
check = False
while (ai < al and bi < bl) and boi < bol:
	if both[boi] < alice[ai] + bob[bi]:
		a += 1
		b += 1
		count += both[boi]
		boi += 1
	else:
		count += alice[ai] + bob[bi]
		ai += 1
		bi += 1
		a += 1
		b += 1
	if a >= k and b >= k:
		check = True
		break
if check:
	print(count)
elif boi == bol:
	na = k - a
	if al - ai >= na:
		for i in range(max(na, 0)):
			count += alice[ai + i]
		nb = k - b
		if bl - bi >= nb:
			for i in range(max(nb, 0)):
				count += bob[bi + i]
			print(count)
		else:
			print('-1')
	else:
		print('-1')
elif ai == al:
	na = k - a
	if bol - boi >= na:
		for i in range(max(na, 0)):
			count += both[boi + i]
			b += 1
		nb = k - b
		if bl + bol - boi - bi >= nb:
			l = []
			for i in range(boi, min(bol, boi + max(nb, 0))):
				l.append(both[i])
			for i in range(bi, min(bl, bi + max(nb, 0))):
				l.append(bob[i])
			l.sort()
			for i in range(max(nb, 0)):
				count += l[i]
			print(count)
		else:
			print('-1')
	else:
		print('-1')
else:
	nb = k - b
	if bol - boi >= nb:
		for i in range(max(nb, 0)):
			count += both[boi + i]
			a += 1
		na = k - a
		if al + bol - boi - ai >= na:
			l = []
			for i in range(boi, min(bol, boi + max(na, 0))):
				l.append(both[i])
			for i in range(ai, min(al, ai + max(na, 0))):
				l.append(alice[i])
			l.sort()
			for i in range(max(na, 0)):
				count += l[i]
			print(count)
		else:
			print('-1')
	else:
		print('-1')


(n, k) = map(int, input().split())
a = []
b = []
c = []
c1 = []
for i in range(n):
	(q, w, e) = map(int, input().split())
	if w == 1 and e == 1:
		c.append(q)
	if w == 1 and e == 0:
		a.append(q)
	if w == 0 and e == 1:
		b.append(q)
a = sorted(a)
b = sorted(b)
for i in range(min(len(a), len(b))):
	c.append(a[i] + b[i])
c = sorted(c)
if len(c) < k:
	print(-1)
	exit(0)
s = 0
for i in range(k):
	s += c[i]
print(s)


(n, k) = map(int, input().split())
x = []
y = []
z = []
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		x.append(t)
	elif a == 1 and b == 0:
		y.append(t)
	elif a == 0 and b == 1:
		z.append(t)
if len(x) >= k or (k - len(x) <= len(y) and k - len(x) <= len(z)):
	x.sort()
	y.sort()
	z.sort()
	i = 0
	j = 0
	ans = 0
	while i + j < k:
		if i < len(x) and j < len(y) and (j < len(z)):
			if x[i] < y[j] + z[j]:
				ans = ans + x[i]
				i = i + 1
			else:
				ans = ans + y[j] + z[j]
				j = j + 1
		elif i < len(x):
			ans = ans + x[i]
			i = i + 1
		elif j < len(y) and j < len(z):
			ans = ans + y[j] + z[j]
			j = j + 1
	print(ans)
else:
	print('-1')


(n, k) = map(int, input().split())
t = list()
a = list()
b = list()
alice = list()
bob = list()
both = list()
for i in range(0, n):
	(x, y, z) = map(int, input().split())
	if y and z:
		both.append(x)
	elif y:
		alice.append(x)
	elif z:
		bob.append(x)
alice.sort()
bob.sort()
both.sort()
INF = 200000000000
res = INF
if len(alice) > 1:
	for i in range(1, len(alice)):
		alice[i] += alice[i - 1]
if len(bob) > 1:
	for i in range(1, len(bob)):
		bob[i] += bob[i - 1]
if len(both) > 1:
	for i in range(1, min(k, len(both))):
		both[i] += both[i - 1]
if not len(alice) * len(bob):
	if len(both) < k:
		res = -1
	else:
		res = both[k - 1]
elif not len(both):
	if len(bob) >= k and len(alice) >= k:
		res = bob[k - 1] + alice[k - 1]
	else:
		res = -1
else:
	for cnt in range(1, len(both) + 1):
		if cnt > k:
			break
		i = k - cnt - 1
		if i == -1:
			res = min(res, both[cnt - 1])
			break
		if i < len(alice) and i < len(bob):
			res = min(res, both[cnt - 1] + alice[i] + bob[i])
	if k <= len(alice) and k <= len(bob):
		res = min(res, alice[k - 1] + bob[k - 1])
if res == INF:
	print(-1)
else:
	print(int(res))


(n, k) = map(int, input().split())
(a, b, ab) = ([], [], [])
for _ in range(n):
	(t, x, y) = map(int, input().split())
	if x + y == 2:
		ab.append(t)
	elif x == 1:
		a.append(t)
	elif y == 1:
		b.append(t)
a.sort()
b.sort()
for i in range(min(len(a), len(b))):
	ab.append(a[i] + b[i])
ab.sort()
if len(ab) < k:
	print(-1)
else:
	sum = 0
	for i in range(k):
		sum += ab[i]
	print(sum)


def solve(n, k, a, b, c):
	a.sort()
	b.sort()
	c.sort()
	iab = min(k, len(a), len(b))
	ic = k - iab
	if ic > len(c):
		return -1
	res = 0
	for i in range(ic):
		res += c[i]
	for i in range(iab):
		res += a[i] + b[i]
	iab -= 1
	while ic < len(c) and iab >= 0 and (c[ic] < a[iab] + b[iab]):
		res -= a[iab] + b[iab] - c[ic]
		ic += 1
		iab -= 1
	return res
current_str = input().split(' ')
n = int(current_str[0])
k = int(current_str[1])
a = []
b = []
c = []
for i in range(n):
	current_str = input().split(' ')
	t = int(current_str[0])
	aa = int(current_str[1])
	bb = int(current_str[2])
	if aa and bb:
		c.append(t)
	elif aa:
		a.append(t)
	elif bb:
		b.append(t)
print(solve(n, k, a, b, c))


arr = [int(x) for x in input().split()]
size = arr[0]
total = arr[1]
book_dict = {'2': [], '10': [], '01': []}
for i in range(size):
	book_arr = [int(x) for x in input().split()]
	if book_arr[1] == 1 and book_arr[2] == 1:
		book_dict['2'].append(book_arr[0])
	elif book_arr[1] == 1 and book_arr[2] == 0:
		book_dict['10'].append(book_arr[0])
	elif book_arr[1] == 0 and book_arr[2] == 1:
		book_dict['01'].append(book_arr[0])
count10 = len(book_dict['10'])
count01 = len(book_dict['01'])
count2 = len(book_dict['2'])
result = 0
book_dict['10'].sort()
book_dict['01'].sort()
if count10 + count2 >= total and count01 + count2 >= total:
	for i in range(min(count01, count10)):
		book_dict['2'].append(book_dict['01'][i] + book_dict['10'][i])
	book_dict['2'].sort()
	result = sum(book_dict['2'][:total])
	print(result)
else:
	print(-1)


from sys import stdin
inp = lambda : stdin.readline().strip()
(n, k) = [int(x) for x in inp().split()]
b = []
for _ in range(n):
	b.append([int(x) for x in inp().split()])
both = []
alice = []
bob = []
for i in b:
	if i[1] == 1 and i[2] == 1:
		both.append(i[0])
	elif i[1] == 1:
		alice.append(i[0])
	elif i[2] == 1:
		bob.append(i[0])
if len(alice) + len(both) < k or len(bob) + len(both) < k:
	print(-1)
	exit()
both.sort()
alice.sort()
bob.sort()
b = 0
ind = 0
cost = 0
liked = 0
minimum = min(len(alice), len(bob))
x = max(k - minimum, 0)
for i in range(x):
	if liked == k:
		print(cost)
		exit()
	cost += both[i]
	b += 1
	liked += 1
while True:
	if liked == k:
		print(cost)
		break
	if b < len(both) and ind < len(alice) and (ind < len(bob)) and (both[b] <= alice[ind] + bob[ind]):
		cost += both[b]
		b += 1
	else:
		cost += alice[ind] + bob[ind]
		ind += 1
	liked += 1


(n, k) = map(int, input().split())
oo = list()
oa = list()
ob = list()
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		oo.append(t)
	elif a == 0 and b == 1:
		ob.append(t)
	elif a == 1 and b == 0:
		oa.append(t)
oo = sorted(oo)
oa = sorted(oa)
ob = sorted(ob)
oo_p = 0
oa_p = 0
ob_p = 0
ca = 0
cb = 0
ans = 0
MAX = 23942034809238409823048
if max(0, max(k - len(oa), k - len(ob))) > len(oo):
	print('-1')
	exit(0)

def get_first_elem_from_list(l, pos):
	if pos < len(l):
		return l[pos]
	else:
		return MAX

def remove_first_elem_from_list(l, pos):
	if len(l) > pos:
		pos += 1
	return pos
while ca < k or cb < k:
	oo_f = get_first_elem_from_list(oo, oo_p)
	oa_f = get_first_elem_from_list(oa, oa_p)
	ob_f = get_first_elem_from_list(ob, ob_p)
	if ca < k and cb < k:
		if oo_f <= oa_f + ob_f:
			ca += 1
			cb += 1
			ans += oo_f
			oo_p = remove_first_elem_from_list(oo, oo_p)
		elif oa_f + ob_f < oo_f:
			ca += 1
			cb += 1
			ans += oa_f + ob_f
			oa_p = remove_first_elem_from_list(oa, oa_p)
			ob_p = remove_first_elem_from_list(ob, ob_p)
	elif ca < k:
		if oo_f <= oa_f:
			ca += 1
			ans += oo_f
			oo_p = remove_first_elem_from_list(oo, oo_p)
		elif oa_f < oo_f:
			ca += 1
			ans += oa_f
			oa_p = remove_first_elem_from_list(oa, oa_p)
	elif oo_f <= ob_f:
		cb += 1
		ans += oo_f
		oo_p = remove_first_elem_from_list(oo, oo_p)
	elif ob_f < oo_f:
		cb += 1
		ans += ob_f
		ob_p = remove_first_elem_from_list(ob, ob_p)
print(ans)


(n, k) = map(int, input().split())
lForE = []
lForA = []
lForB = []
cnt = 0
forE = 0
forP = 0
ans = 0
for i in range(n):
	temp = list(map(int, input().split()))
	if temp[1] and temp[2]:
		lForE.append(temp[0])
	elif temp[1] and (not temp[2]):
		lForA.append(temp[0])
	elif not temp[1] and temp[2]:
		lForB.append(temp[0])
lForE.sort()
lForA.sort()
lForB.sort()
while cnt < k and (forP < len(lForB) and forP < len(lForA) or forE < len(lForE)):
	cnt += 1
	if forP < len(lForB) and forP < len(lForA) and (forE < len(lForE)):
		if lForA[forP] + lForB[forP] < lForE[forE]:
			ans += lForA[forP] + lForB[forP]
			forP += 1
		else:
			ans += lForE[forE]
			forE += 1
	elif forE < len(lForE):
		ans += lForE[forE]
		forE += 1
	elif forP < len(lForB) and forP < len(lForA):
		ans += lForA[forP] + lForB[forP]
		forP += 1
if cnt < k:
	print(-1)
else:
	print(ans)


(n, k) = map(int, input().split())
a = []
b = []
s = []
ans = 0
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x == 1 and y == 1:
		s.append(t)
	elif x == 1:
		a.append(t)
	elif y == 1:
		b.append(t)
s1 = len(s)
s2 = len(a)
s3 = len(b)
if s1 + s3 < k:
	print(-1)
elif s1 + s2 < k:
	print(-1)
else:
	s.sort()
	a.sort()
	b.sort()
	i = 0
	j = 0
	v = 0
	while k > 0:
		if s1 == 0:
			ans += a[i] + b[i]
			k -= 1
			s2 -= 1
			s3 -= 1
			i += 1
			j += 1
		elif s2 == 0 or s3 == 0:
			ans += s[v]
			v += 1
			k -= 1
			s1 -= 1
		else:
			k -= 1
			if a[i] + b[j] <= s[v]:
				s2 -= 1
				s3 -= 1
				ans += a[i] + b[j]
				i += 1
				j += 1
			else:
				ans += s[v]
				v += 1
				s1 -= 1
	print(ans)


(n, k) = map(int, input().split())
(ali, bob, both) = ([], [], [])
for i in range(n):
	(r, ai, bi) = map(int, input().split())
	if ai and bi:
		both.append(r)
	elif ai:
		ali.append(r)
	elif bi:
		bob.append(r)
ali.sort()
bob.sort()
for i in range(min(len(ali), len(bob))):
	both.append(ali[i] + bob[i])
if len(both) < k:
	print(-1)
else:
	print(sum(sorted(both)[:k]))


seg = [0] * 200000

def offset(x):
	return x + 100000

def upd(node, L, R, pos, val):
	if L + 1 == R:
		seg[node] += val
		seg[offset(node)] = seg[node] * L
		return
	M = (L + R) // 2
	if pos < M:
		upd(node << 1, L, M, pos, val)
	else:
		upd(node << 1 | 1, M, R, pos, val)
	seg[node] = seg[node << 1] + seg[node << 1 | 1]
	seg[offset(node)] = seg[offset(node << 1)] + seg[offset(node << 1 | 1)]

def query(node, L, R, k):
	if k == 0:
		return [0, 0]
	if seg[node] < k:
		return [seg[offset(node)], seg[node]]
	if L + 1 == R:
		return [L * k, k]
	M = (L + R) // 2
	left = query(node << 1, L, M, k)
	right = query(node << 1 | 1, M, R, k - left[1])
	left[0] += right[0]
	left[1] += right[1]
	return left
(n, m, k) = map(int, input().split())
(A, B, both, neither) = ([], [], [], [])
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 0 and b == 0:
		neither.append([t, i + 1])
	if a == 1 and b == 0:
		A.append([t, i + 1])
	if a == 0 and b == 1:
		B.append([t, i + 1])
	if a == 1 and b == 1:
		both.append([t, i + 1])
	upd(1, 0, 10001, t, 1)
A.sort()
B.sort()
both.sort()
p1 = min(k, len(both))
p2 = k - p1
if 2 * k - p1 > m or p2 > min(len(A), len(B)):
	print(-1)
	exit(0)
(sum, ans, ch) = (0, 2 ** 31, p1)
for i in range(p1):
	sum += both[i][0]
	upd(1, 0, 10001, both[i][0], -1)
for i in range(p2):
	sum += A[i][0] + B[i][0]
	upd(1, 0, 10001, A[i][0], -1)
	upd(1, 0, 10001, B[i][0], -1)
ans = sum + query(1, 0, 10001, m - 2 * k + p1)[0]
while p1 > 0:
	if p2 == min(len(A), len(B)):
		break
	upd(1, 0, 10001, A[p2][0], -1)
	sum += A[p2][0]
	upd(1, 0, 10001, B[p2][0], -1)
	sum += B[p2][0]
	upd(1, 0, 10001, both[p1 - 1][0], 1)
	sum -= both[p1 - 1][0]
	p2 += 1
	p1 -= 1
	if m - 2 * k + p1 < 0:
		break
	Q = query(1, 0, 10001, m - 2 * k + p1)
	if ans > sum + Q[0]:
		ans = sum + Q[0]
		ch = p1
print(ans)
ind = [both[i][1] for i in range(ch)] + [A[i][1] for i in range(k - ch)] + [B[i][1] for i in range(k - ch)]
st = neither + [both[i] for i in range(ch, len(both))] + [A[i] for i in range(k - ch, len(A))] + [B[i] for i in range(k - ch, len(B))]
st.sort()
ind += [st[i][1] for i in range(m - 2 * k + ch)]
print(' '.join([str(x) for x in ind]))


import sys
input = sys.stdin.buffer.readline

def solution():
	a = []
	b = []
	c = []
	(n, k) = map(int, input().split())
	for i in range(n):
		(t, x, y) = map(int, input().split())
		if x == 1 and y == 1:
			c.append(t)
		elif x == 1:
			a.append(t)
		elif y == 1:
			b.append(t)
	a.sort()
	b.sort()
	c.sort()
	ans = 0
	if len(a) + len(c) < k or len(b) + len(c) < k:
		print(-1)
	else:
		z = 0
		i = 0
		j = 0
		while k > 0:
			if i < len(c) and j < min(len(a), len(b)):
				if a[j] + b[j] <= c[i]:
					ans += a[j] + b[j]
					j += 1
				else:
					ans += c[i]
					i += 1
			elif i < len(c):
				ans += c[i]
				i += 1
			else:
				ans += a[j] + b[j]
				j += 1
			k -= 1
		print(ans)
solution()


from math import inf
(n, k) = map(int, input().split())
dic = {'11': [], '10': [], '01': []}
for _ in range(n):
	(a, b, c) = input().split()
	a = int(a)
	if b == '1' or c == '1':
		dic[b + c].append(a)
dic['11'].sort()
dic['10'].sort()
dic['01'].sort()
sums = {'11': [0], '10': [0], '01': [0]}
for i in dic:
	for j in dic[i]:
		sums[i].append(sums[i][-1] + j)
total = inf
for i in range(min(k + 1, len(sums['11']))):
	number = k - i
	if number < len(sums['10']) and number < len(sums['01']):
		total = min(total, sums['11'][i] + sums['10'][number] + sums['01'][number])
if total == inf:
	print(-1)
else:
	print(total)


(n, k) = list(map(int, input().split()))
(time, A, B, AB, lenA, lenB, lenAB) = ([], [], [], [], 0, 0, 0)
for idx in range(n):
	(t, a, b) = list(map(int, input().split()))
	time.append(t)
	if a and (not b):
		A.append(t)
		lenA += 1
	elif b and (not a):
		B.append(t)
		lenB += 1
	elif a and b:
		AB.append(t)
		lenAB += 1
if lenA + lenAB < k or lenB + lenAB < k:
	print(-1)
else:
	A.sort()
	B.sort()
	AB.sort()
	(s, x, y) = (0, 0, 0)
	for i in range(k):
		if x < lenA and x < lenB and (y < lenAB):
			if A[x] + B[x] < AB[y]:
				s += A[x] + B[x]
				x += 1
			else:
				s += AB[y]
				y += 1
		elif x >= lenA or x >= lenB:
			s += AB[y]
			y += 1
		elif y >= lenAB and x < lenA and (x < lenB):
			s += A[x] + B[x]
			x += 1
	print(s)


a11 = []
a10 = []
a01 = []
(n, m) = map(int, input().split())
for i in range(n):
	(a, b, c) = map(int, input().split())
	if b == 1:
		if c == 1:
			a11.append(a)
		else:
			a10.append(a)
	elif c == 1:
		a01.append(a)
	else:
		pass
ln1 = len(a11)
ln2 = len(a10)
ln3 = len(a01)
if ln1 + ln2 < m or ln1 + ln3 < m:
	print('-1')
else:
	a11.sort()
	a10.sort()
	a01.sort()
	p1 = p2 = 0
	cnt = 0
	for i in range(m):
		if p1 < ln1 and p2 < min(ln2, ln3):
			if a11[p1] <= a10[p2] + a01[p2]:
				cnt += a11[p1]
				p1 += 1
			else:
				cnt += a10[p2] + a01[p2]
				p2 += 1
		elif p1 < ln1:
			cnt += a11[p1]
			p1 += 1
		else:
			cnt += a10[p2] + a01[p2]
			p2 += 1
	print(cnt)


def cta(t, p, r):
	global ana, iva, an
	ana[iva[t][p][1]] ^= True
	an += iva[t][p][0] * r
(n, m, k) = [int(x) for x in input().split()]
iva = [[] for _ in range(4)]
alv = [() for _ in range(n)]
for i in range(n):
	(v, o, u) = [int(x) for x in input().split()]
	q = o << 1 | u
	iva[q].append((v, i))
	alv[i] = (v, i)
for e in iva:
	e.sort()
alv.sort()
(ct, a, r, ps, an) = (0, 0, 0, min(len(iva[1]), len(iva[2])), 0)
ana = [False] * n
for _ in range(k):
	if a < ps and r < len(iva[3]):
		if iva[1][a][0] + iva[2][a][0] < iva[3][r][0]:
			cta(1, a, 1)
			cta(2, a, 1)
			ct += 2
			a += 1
		else:
			cta(3, r, 1)
			ct += 1
			r += 1
	elif a < ps:
		cta(1, a, 1)
		cta(2, a, 1)
		ct += 2
		a += 1
	elif r < len(iva[3]):
		cta(3, r, 1)
		ct += 1
		r += 1
	else:
		print(-1)
		exit(0)
while ct > m and a > 0 and (r < len(iva[3])):
	a -= 1
	cta(1, a, -1)
	cta(2, a, -1)
	cta(3, r, 1)
	ct -= 1
	r += 1
ap = 0
while ct < m and ap < n:
	if not ana[alv[ap][1]]:
		if r > 0 and a < ps and (iva[1][a][0] + iva[2][a][0] - iva[3][r - 1][0] < alv[ap][0]):
			if ana[iva[1][a][1]] or ana[iva[2][a][1]]:
				a += 1
				continue
			r -= 1
			cta(1, a, 1)
			cta(2, a, 1)
			cta(3, r, -1)
			a += 1
			ct += 1
		else:
			ct += 1
			an += alv[ap][0]
			ana[alv[ap][1]] = True
			ap += 1
	else:
		ap += 1
if ct != m:
	print(-1)
else:
	print(an)
	for i in range(n):
		if ana[i]:
			print(i + 1, end=' ')


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(n, k) = I()
a = []
b = []
ab = []
for _ in range(n):
	(x, y, z) = I()
	if y and z:
		ab.append(x)
	elif y:
		a.append(x)
	elif z:
		b.append(x)
a.sort()
b.sort()
ab.sort()
(x, y, z) = (len(a), len(b), len(ab))
i = j = l = t = an = 0
if x + z < k or y + z < k:
	print(-1)
else:
	while t != k:
		if i >= x or j >= y:
			an += ab[l]
			l += 1
		elif l >= z:
			an += a[i] + b[j]
			i += 1
			j += 1
		elif a[i] + b[j] < ab[l]:
			an += a[i] + b[j]
			i += 1
			j += 1
		else:
			an += ab[l]
			l += 1
		t += 1
	print(an)


def mi():
	return map(int, input().split())
(n, k) = mi()
(a, b, ab) = ([], [], [])
for i in range(n):
	(t, al, bl) = mi()
	(lab, la, lb) = (0, 0, 0)
	if al and bl:
		ab.append(t)
	elif al:
		a.append(t)
	elif bl:
		b.append(t)
(b.sort(), a.sort(), ab.sort())
(la, lb, lab) = (len(a), len(b), len(ab))
for i in range(1, lb):
	b[i] += b[i - 1]
for i in range(1, la):
	a[i] += a[i - 1]
ans = 10000000000.0
if len(a) >= k and len(b) >= k:
	ans = a[k - 1] + b[k - 1]
for i in range(lab):
	if i > 0:
		ab[i] += ab[i - 1]
	if not k - 1 - i:
		ans = min(ans, ab[i])
	if k - 1 - i > 0 and min(len(a), len(b)) >= k - 1 - i:
		ans = min(ans, ab[i] + a[k - i - 2] + b[k - i - 2])
if ans == 10000000000.0:
	ans = -1
print(ans)


import sys
input = sys.stdin.readline

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def upper_bound(a, x, lo=0):
	hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(1000000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

def int_array():
	return list(map(int, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
(n, k) = int_array()
a = []
sum_a = sum_b = 0
for __ in range(n):
	(t, aa, bb) = int_array()
	sum_a += aa
	sum_b += bb
	a.append((t, aa, bb))
if sum_a < k or sum_b < k:
	print(-1)
else:
	only_a = []
	only_b = []
	both = []
	for i in a:
		if i[1] == 1 and i[2] == 0:
			only_a.append(i[0])
		elif i[1] == 0 and i[2] == 1:
			only_b.append(i[0])
		elif i[1] == 1 and i[2] == 1:
			both.append(i[0])
	only_a.sort()
	only_b.sort()
	for i in range(min(len(only_a), len(only_b))):
		both.append(only_a[i] + only_b[i])
	both.sort()
	print(sum(both[:k]))


import math
import os
import random
import re
import sys
import heapq
(n, k) = map(int, input().split())
a = []
b = []
ab = []
for _ in range(n):
	(t, av, bv) = map(int, input().split())
	if av == 1 and bv == 1:
		ab.append(t)
	elif av == 1:
		a.append(t)
	elif bv == 1:
		b.append(t)
a = sorted(a, reverse=True)
b = sorted(b, reverse=True)
ab = sorted(ab, reverse=True)
ans = 0
infi = 10 ** 5
possible = True
for _ in range(k):
	if len(ab) == 0 and (len(a) == 0 or len(b) == 0):
		possible = False
		break
	at = a[-1] if len(a) > 0 else infi
	bt = b[-1] if len(b) > 0 else infi
	abt = ab[-1] if len(ab) > 0 else infi
	if at + bt < abt:
		ans += at + bt
		a.pop()
		b.pop()
	else:
		ans += abt
		ab.pop()
if possible:
	print(ans)
else:
	print(-1)


import sys
import math

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_string():
	return sys.stdin.readline().strip()
(n, k) = get_ints()
alice = []
bob = []
comm = []
for i in range(n):
	(t, a, b) = get_ints()
	if a == 1 and b == 1:
		comm.append(t)
		continue
	if a == 1:
		alice.append(t)
	if b == 1:
		bob.append(t)
alice.sort()
(bob.sort(), comm.sort())
ans = 0
ptr1 = 0
ptr2 = 0
fans = []
while ptr1 < min(len(alice), len(bob)) and ptr2 < len(comm):
	if alice[ptr1] + bob[ptr1] < comm[ptr2]:
		fans.append(alice[ptr1] + bob[ptr1])
		ptr1 += 1
	else:
		fans.append(comm[ptr2])
		ptr2 += 1
while ptr1 < min(len(alice), len(bob)):
	fans.append(alice[ptr1] + bob[ptr1])
	ptr1 += 1
while ptr2 < len(comm):
	fans.append(comm[ptr2])
	ptr2 += 1
if len(fans) < k:
	print(-1)
else:
	print(sum(fans[0:k]))


from sys import *
(n, k) = [int(x) for x in stdin.readline().split()]
lk1 = []
lk2 = []
lk3 = []
for _ in range(n):
	(time, x, y) = [int(x) for x in stdin.readline().split()]
	if x == 1 and y == 1:
		lk3.append(time)
	elif x == 1:
		lk1.append(time)
	elif y == 1:
		lk2.append(time)
lk1.sort()
lk2.sort()
cnt = min(len(lk1), len(lk2))
for i in range(cnt):
	lk3.append(lk1[i] + lk2[i])
lk3.sort()
if len(lk3) < k:
	stdout.write(str(-1) + '\n')
else:
	sum = 0
	for i in range(k):
		sum += lk3[i]
	stdout.write(str(sum) + '\n')


import sys, math, os
from io import BytesIO, IOBase
from collections import defaultdict as dd, deque, Counter

def data():
	return sys.stdin.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
INF = 10 ** 9
mod = 998244353
(n, k) = mdata()
(a, b, c, d) = ([], [], [], [])
for i in range(n):
	(t1, a1, b1) = mdata()
	if a1 == 1 and b1 == 1:
		c.append(t1)
	elif a1 == 1:
		a.append(t1)
	elif b1 == 1:
		b.append(t1)
	else:
		d.append(t1)
a.sort(reverse=True)
b.sort(reverse=True)
c.sort(reverse=True)
d.sort(reverse=True)
ans = 0
while k:
	if len(a) != 0 and len(b) != 0:
		if len(c) != 0:
			if c[-1] < a[-1] + b[-1]:
				ans += c.pop()
			else:
				ans += a.pop() + b.pop()
		else:
			ans += a.pop() + b.pop()
	elif len(c) != 0:
		ans += c.pop()
	else:
		break
	k -= 1
if k != 0:
	out(-1)
else:
	out(ans)


import sys
import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(n, k) = map(int, input().split())
bothlike = []
alike = []
blike = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		bothlike.append(t)
	if a == 1 and b == 0:
		alike.append(t)
	if a == 0 and b == 1:
		blike.append(t)
if len(alike) + len(bothlike) < k or len(blike) + len(bothlike) < k:
	print(-1)
	sys.exit()
alike.sort()
blike.sort()
bothlike.sort()
asum = [0]
current = 0
for i in range(len(alike)):
	current += alike[i]
	asum.append(current)
bsum = [0]
current = 0
for i in range(len(blike)):
	current += blike[i]
	bsum.append(current)
bothcurrent = 0
ans = 10 ** 18
alen = len(alike)
blen = len(blike)
bothlen = len(bothlike)
for i in range(bothlen + 1):
	if i > 0:
		bothcurrent += bothlike[i - 1]
	if i > k:
		break
	if k - i > alen or k - i > blen:
		continue
	ans = min(ans, asum[k - i] + bsum[k - i] + bothcurrent)
print(ans)


(n, k) = map(int, input().split())
(ab, a, b) = ([], [], [])
for _ in range(n):
	(t, aa, bb) = map(int, input().split())
	if aa and bb:
		ab.append(t)
	elif aa:
		a.append(t)
	elif bb:
		b.append(t)
a.sort()
b.sort()
zz = min(len(a), len(b))
for i in range(zz):
	ab.append(a[i] + b[i])
print(-1 if len(ab) < k else sum(sorted(ab)[:k]))


(n, k) = list(map(int, input().split(' ')))
db = []
a = []
b = []
for i in range(n):
	(t, A, B) = list(map(int, input().split(' ')))
	if A == B == 1:
		db.append(t)
	elif A == 1:
		a.append(t)
	elif B == 1:
		b.append(t)
a.sort()
b.sort()
for i in range(min(len(a), len(b))):
	db.append(a[i] + b[i])
if len(db) < k:
	print(-1)
else:
	db.sort()
	print(sum(db[:k]))


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


ve1 = []
ve2 = []
ve3 = []
s = input()
(n, k) = map(int, s.split(' '))
num1 = 0
num2 = 0
for i in range(0, n):
	s = input()
	(t, a, b) = map(int, s.split(' '))
	if a & b:
		ve3.append(t)
		num1 = num1 + 1
		num2 = num2 + 1
	elif a == 0 and b == 1:
		ve2.append(t)
		num2 = num2 + 1
	elif a == 1 and b == 0:
		ve1.append(t)
		num1 = num1 + 1
ve1.sort()
ve2.sort()
ve3.sort()
if num1 < k or num2 < k:
	print(-1)
	exit()
num = 0
num1 = 0
num2 = 0
Sum = 0
while num < k:
	if num1 < len(ve1) and num1 < len(ve2) and (num2 < len(ve3)):
		if ve1[num1] + ve2[num1] <= ve3[num2]:
			Sum = Sum + ve1[num1] + ve2[num1]
			num1 = num1 + 1
		else:
			Sum = Sum + ve3[num2]
			num2 = num2 + 1
		num = num + 1
	else:
		break
if num == k:
	print(Sum)
	exit()
if num2 < len(ve3):
	while num < k:
		Sum = Sum + ve3[num2]
		num2 = num2 + 1
		num = num + 1
else:
	while num < k:
		Sum = Sum + ve1[num1] + ve2[num1]
		num1 = num1 + 1
		num = num + 1
print(Sum)


import sys
input = sys.stdin.readline

def solve(alice, bob, both, k):
	both.sort(key=lambda x: x[0], reverse=True)
	alice.sort(key=lambda x: x[0], reverse=True)
	bob.sort(key=lambda x: x[0], reverse=True)
	count = 0
	ans = 0
	while both and alice and bob:
		if both[-1][0] <= alice[-1][0] + bob[-1][0]:
			ans += both[-1][0]
			both.pop()
		else:
			ans += alice[-1][0] + bob[-1][0]
			alice.pop()
			bob.pop()
		count += 1
		if count == k:
			return ans
	while both:
		ans += both[-1][0]
		both.pop()
		count += 1
		if count == k:
			return ans
	while alice and bob:
		ans += alice[-1][0] + bob[-1][0]
		alice.pop()
		bob.pop()
		count += 1
		if count == k:
			return ans
	return -1
(n, k) = map(int, input().split())
both = []
alice = []
bob = []
for _ in range(n):
	book = list(map(int, input().split()))
	if book[1] == 1 and book[2] == 1:
		both.append(book)
	elif book[1] == 1:
		alice.append(book)
	elif book[2] == 1:
		bob.append(book)
if len(both) + min(len(alice), len(bob)) < k:
	print(-1)
else:
	print(solve(alice, bob, both, k))


import sys
input = sys.stdin.readline
import heapq
import copy
import math
import decimal

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def insr2():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())

def pr_list(a):
	print(*a, sep=' ')

def main():
	tests = 1
	limit = 10 ** 18
	ans = 0
	for test in range(tests):
		[n, k] = inlt()
		b = []
		a = []
		both = []
		for i in range(n):
			[t, alice, bob] = inlt()
			if alice == 1 and bob == 1:
				both.append(t)
			elif alice == 1:
				a.append(t)
			elif bob == 1:
				b.append(t)
		both.sort()
		a.sort()
		b.sort()
		if len(both) + len(a) < k or len(both) + len(b) < k:
			print(-1)
			break
		ans = 0
		a_i = 0
		b_i = 0
		both_i = 0
		for _ in range(k):
			if both_i != len(both) and a_i != len(a) and (b_i != len(b)):
				if both[both_i] < a[a_i] + b[b_i]:
					ans = ans + both[both_i]
					both_i += 1
				else:
					ans = ans + a[a_i] + b[b_i]
					a_i = a_i + 1
					b_i = b_i + 1
			elif both_i == len(both):
				ans = ans + a[a_i] + b[b_i]
				a_i = a_i + 1
				b_i = b_i + 1
			else:
				ans = ans + both[both_i]
				both_i += 1
		print(ans)
main()


line = input()
(n, m, k) = [int(i) for i in line.split(' ')]
(books, allL, aliceL, bobL, other) = (list(range(1, n + 1)), [], [], [], [])
ts = [[] for _ in range(n + 1)]
for i in range(n):
	line = input()
	(t, a, b) = [int(j) for j in line.split(' ')]
	ts[i + 1] = [t, a, b]
	if a == 1 and b == 1:
		allL.append(i + 1)
	elif a == 1:
		aliceL.append(i + 1)
	elif b == 1:
		bobL.append(i + 1)
	else:
		other.append(i + 1)
if len(allL) + min(len(aliceL), len(bobL)) < k or (len(allL) < k and 2 * (k - len(allL)) > m - len(allL)):
	print(-1)
	exit()
books.sort(key=lambda x: (ts[x][0], -ts[x][2] * ts[x][1]))
allL.sort(key=lambda x: (ts[x][0], -ts[x][2] * ts[x][1]))
aliceL.sort(key=lambda x: (ts[x][0], -ts[x][2] * ts[x][1]))
bobL.sort(key=lambda x: (ts[x][0], -ts[x][2] * ts[x][1]))
other.sort(key=lambda x: (ts[x][0], -ts[x][2] * ts[x][1]))
x = max(2 * k - m, 0, k - min(len(aliceL), len(bobL)), m - len(aliceL) - len(bobL) - len(other))
(cura, curb, curo, cur) = (max(0, k - x), max(0, k - x), 0, sum((ts[i][0] for i in allL[:x])))
cur += sum((ts[i][0] for i in aliceL[:cura])) + sum((ts[i][0] for i in bobL[:curb]))
while cura + x + curb + curo < m:
	an = ts[aliceL[cura]][0] if cura < len(aliceL) else 9999999999
	bn = ts[bobL[curb]][0] if curb < len(bobL) else 9999999999
	on = ts[other[curo]][0] if curo < len(other) else 9999999999
	cur += min(an, bn, on)
	if an <= bn and an <= on:
		cura += 1
	elif bn <= an and bn <= on:
		curb += 1
	else:
		curo += 1
(res, a, b, o) = (cur, cura, curb, curo)
for i in range(x + 1, len(allL) + 1):
	cur += ts[allL[i - 1]][0]
	if cura > 0:
		cura -= 1
		cur -= ts[aliceL[cura]][0]
	if curb > 0:
		curb -= 1
		cur -= ts[bobL[curb]][0]
	if curo > 0:
		curo -= 1
		cur -= ts[other[curo]][0]
	while cura + i + curb + curo < m:
		an = ts[aliceL[cura]][0] if cura < len(aliceL) else 9999999999
		bn = ts[bobL[curb]][0] if curb < len(bobL) else 9999999999
		on = ts[other[curo]][0] if curo < len(other) else 9999999999
		cur += min(an, bn, on)
		if an <= bn and an <= on:
			cura += 1
		elif bn <= an and bn <= on:
			curb += 1
		else:
			curo += 1
	if res > cur:
		(res, x, a, b, o) = (cur, i, cura, curb, curo)
print(res)
for i in range(x):
	print(allL[i], end=' ')
for i in range(a):
	print(aliceL[i], end=' ')
for i in range(b):
	print(bobL[i], end=' ')
for i in range(o):
	print(other[i], end=' ')


import collections as cc
import math as mt
import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(n, k) = I()
a = []
for i in range(n):
	a.append(I())
a.sort()
both = []
bs = 0
f = 0
for i in range(n):
	if a[i][1] and a[i][2]:
		both.append(a[i][0])
al = []
bo = []
for i in range(n):
	if a[i][1] and (not a[i][2]):
		al.append(a[i][0])
	elif a[i][2] and (not a[i][1]):
		bo.append(a[i][0])
su = []
for i in range(min(len(al), len(bo))):
	su.append(al[i] + bo[i])
xx = len(both)
yy = len(su)
if xx + yy < k:
	print(-1)
elif both and (not su):
	if xx >= k:
		print(sum(both[:k]))
	else:
		print(-1)
elif su and (not both):
	if yy >= k:
		print(sum(su[:k]))
	else:
		print(-1)
else:
	te = both + su
	te.sort()
	print(sum(te[:k]))


def main():
	(n, k) = map(int, input().split(' '))
	ta = []
	tb = []
	tc = []
	for i in range(n):
		(t, a, b) = map(int, input().split(' '))
		if a == 1 and b == 1:
			tc.append(t)
		elif a == 1:
			ta.append(t)
		elif b == 1:
			tb.append(t)
	ta.sort()
	tb.sort()
	tc.sort()
	if len(ta) + len(tc) < k or len(tb) + len(tc) < k:
		return -1
	ta.append(10 ** 5)
	tb.append(10 ** 5)
	tc.append(10 ** 5)
	na = 0
	nb = 0
	nc = 0
	T = 0
	while na + nc < k and nb + nc < k:
		while tc[nc] <= ta[na] + tb[nb]:
			T += tc[nc]
			nc += 1
			if na + nc >= k and nb + nc >= k:
				return T
		if na + nc < k:
			T += ta[na]
			na += 1
		if nb + nc < k:
			T += tb[nb]
			nb += 1
		while nb + nc >= k and na + nc < k:
			if tc[nc] <= ta[na]:
				T += tc[nc]
				nc += 1
			else:
				T += ta[na]
				na += 1
		while na + nc >= k and nb + nc < k:
			if tc[nc] <= tb[nb]:
				T += tc[nc]
				nc += 1
			else:
				T += tb[nb]
				nb += 1
	return T
print(main())


(n, k) = [int(j) for j in input().split()]
al = bo = 0
both = []
sial = []
sibob = []
for i in range(n):
	(tim, alice, bob) = [int(j) for j in input().split()]
	if alice == 1 and bob == 1:
		both.append(tim)
		al += 1
		bo += 1
	elif alice == 1:
		sial.append(tim)
		al += 1
	elif bob == 1:
		sibob.append(tim)
		bo += 1
if al < k or bo < k:
	print(-1)
else:
	both.sort()
	sial.sort()
	sibob.sort()
	bsize = bosize = alsize = count = ans = cntboth = cntsial = cntsibob = 0
	bsize = len(both)
	alsize = len(sial)
	bosize = len(sibob)
	while count != k:
		if cntboth < bsize and cntsial < alsize and (cntboth < bosize):
			if both[cntboth] <= sial[cntsial] + sibob[cntsibob]:
				ans += both[cntboth]
				cntboth += 1
			else:
				ans += sial[cntsial] + sibob[cntsibob]
				cntsial += 1
				cntsibob += 1
		elif cntboth >= bsize and cntsial < alsize and (cntsibob < bosize):
			ans += sial[cntsial] + sibob[cntsibob]
			cntsial += 1
			cntsibob += 1
		elif cntboth < bsize and (cntsial >= alsize or cntboth >= bosize):
			ans += both[cntboth]
			cntboth += 1
		count += 1
	print(ans)


from heapq import *
from collections import *
import os
import sys
from io import BytesIO, IOBase
import math
ins = lambda : [int(x) for x in input()]
inp = lambda : int(input())
inps = lambda : [int(x) for x in input().split()]

def main():
	(n, k) = inps()
	bks = [[0] for i in range(4)]
	for i in range(n):
		(t, a, b) = inps()
		bks[2 * a + b].append(t)
	for i in range(4):
		bks[i].sort()
	for i in range(4):
		for j in range(len(bks[i]) - 1):
			bks[i][j + 1] += bks[i][j]
	ans = float('inf')
	for i in range(k + 1):
		if len(bks[3]) > i and len(bks[1]) > k - i and (len(bks[2]) > k - i):
			ans = min(ans, bks[3][i] + bks[1][k - i] + bks[2][k - i])
	if ans != float('inf'):
		print(ans)
	else:
		print(-1)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
import math

def II():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def MI():
	return list(map(int, sys.stdin.readline().split()))

def SI():
	return sys.stdin.readline().strip()
(n, k) = MI()
x = []
y = []
z = []
o = []
for q in range(n):
	(t, a, b) = MI()
	if a == 1 and b == 1:
		z.append(t)
	elif a == 1:
		x.append(t)
	elif b == 1:
		y.append(t)
	else:
		o.append(t)
x.sort()
y.sort()
z.sort()
x0 = len(x)
y0 = len(y)
z0 = len(z)
if x0 + z0 < k or y0 + z0 < k:
	print(-1)
else:
	ans = 0
	l = r = 0
	for i in range(k):
		if l < x0 and l < y0 and (r < z0):
			if x[l] + y[l] < z[r]:
				ans += x[l] + y[l]
				l += 1
			else:
				ans += z[r]
				r += 1
		elif r < z0:
			ans += z[r]
			r += 1
		elif l < x0 and l < y0:
			ans += x[l] + y[l]
			l += 1
	print(ans)


import sys
input = lambda : sys.stdin.buffer.readline().rstrip()
(q, w) = map(int, input().split())
e = []
r = []
t = []
z = 0
x = 0
for i in range(q):
	(a, b, c) = map(int, input().split())
	if b == 1 and c == 1:
		e.append(a)
		z += 1
		x += 1
	elif b == 1 and c == 0:
		r.append(a)
		x += 1
	elif b == 0 and c == 1:
		t.append(a)
		z += q
r = sorted(r)
t = sorted(t)
for i in range(min(len(r), len(t))):
	e.append(r[i] + t[i])
e = sorted(e)
i = 0
t = 0
k = 0
b = len(e)
if b < w:
	print(-1)
else:
	while i < w:
		if t < b:
			k += e[t]
			t += 1
		i += 1
	print(k)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
(n, k) = Ri()
lis = []
a = []
b = []
ab = []
for i in range(n):
	temp = Ri()
	if temp[1] != 0 or temp[2] != 0:
		if temp[1] != 0 and temp[2] != 0:
			ab.append(temp[0])
		elif temp[1] != 0:
			a.append(temp[0])
		else:
			b.append(temp[0])
ab.sort()
a.sort()
b.sort()
if len(ab) + len(a) < k or len(ab) + len(b) < k:
	print(-1)
else:
	ans = 0
	totans = 0
	(curab, cura, curb) = (0, 0, 0)
	while ans < k:
		if len(a) == cura or len(b) == curb:
			ans += 1
			totans += ab[curab]
			curab += 1
		elif len(ab) == curab:
			ans += 1
			totans += a[cura] + b[curb]
			cura += 1
			curb += 1
		elif ab[curab] > a[cura] + b[curb]:
			ans += 1
			totans += a[cura] + b[curb]
			cura += 1
			curb += 1
		else:
			ans += 1
			totans += ab[curab]
			curab += 1
	print(totans)


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(n, k) = map(int, input().split())
bookA = []
bookB = []
bookAB = []
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		bookAB.append(t)
	elif a == 1:
		bookA.append(t)
	elif b == 1:
		bookB.append(t)
bookA.sort()
bookB.sort()
bookAB.sort()
bookASum = [0]
bookBSum = [0]
bookABSum = [0]
for elem in bookA:
	bookASum.append(bookASum[-1] + elem)
for elem in bookB:
	bookBSum.append(bookBSum[-1] + elem)
for elem in bookAB:
	bookABSum.append(bookABSum[-1] + elem)
minReadingTime = -1
for i in range(len(bookABSum)):
	if len(bookASum) > max(k - i, 0) and len(bookBSum) > max(k - i, 0) and (len(bookABSum) > i):
		if minReadingTime == -1 or minReadingTime > bookABSum[i] + bookASum[max(k - i, 0)] + bookBSum[max(k - i, 0)]:
			minReadingTime = bookABSum[i] + bookASum[max(k - i, 0)] + bookBSum[max(k - i, 0)]
print(minReadingTime)


(n, k) = map(int, input().split())
at = []
bt = []
both = []
f = 0
for x in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1:
		at.append(t)
	elif b == 1:
		bt.append(t)
at.sort()
bt.sort()
both.sort()
i = 0
j = 0
if len(at) + len(both) < k or len(bt) + len(both) < k:
	f = -1
else:
	for x in range(k):
		if i >= len(at) or i >= len(bt):
			i = -1
		if j >= len(both):
			j = -1
		if i == -1:
			f += both[j]
			j += 1
		elif j == -1:
			f += at[i] + bt[i]
			i += 1
		elif at[i] + bt[i] < both[j]:
			f += at[i] + bt[i]
			i += 1
		else:
			f += both[j]
			j += 1
print(f)


import math
from collections import *
import sys
from functools import reduce

def get_ints():
	return map(int, input().strip().split())

def get_list():
	return list(get_ints())

def getlistofstring():
	return list(input().strip().split())

def printxsp(*args):
	return print(*args, end='')

def printsp(*args):
	return print(*args, end=' ')
UGLYMOD = int(1000000000.0) + 7
SEXYMOD = 998244353
MAXN = int(100000.0)
alice = []
bob = []
both = []
(n, k) = get_ints()
for i in range(n):
	(t, a, b) = get_ints()
	if a & b:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
if len(both) + min(len(alice), len(bob)) < k:
	ans = -1
else:
	bob = sorted(bob)
	alice = sorted(alice)
	both = sorted(both)
	ai = bi = xi = 0
	ans = 0
	while k:
		try:
			X = both[xi]
		except:
			X = float('inf')
		try:
			A = alice[ai]
		except:
			A = float('inf')
		try:
			B = bob[bi]
		except:
			B = float('inf')
		if A == float('inf') or B == float('inf'):
			ans += X
			xi += 1
		elif X == float('inf'):
			ans += A + B
			ai += 1
			bi += 1
		elif A + B < X:
			ans += A + B
			ai += 1
			bi += 1
		else:
			ans += X
			xi += 1
		k -= 1
print(ans)


(n, k) = map(int, input().split())
alice = []
bob = []
comm = []
for _ in range(n):
	(a, b, c) = map(int, input().split())
	if b == 1 and c == 1:
		comm.append(a)
	elif b == 1 and c == 0:
		alice.append(a)
	elif b == 0 and c == 1:
		bob.append(a)
alice.sort()
bob.sort()
for i in range(min(len(alice), len(bob))):
	comm.append(alice[i] + bob[i])
comm.sort()
if len(comm) < k:
	print(-1)
else:
	print(sum(comm[:k]))


(n, k) = map(int, input().split())
(both, f, s) = ([], [], [])
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x == 1 and y == 1:
		both.append(t)
	elif x == 1:
		f.append(t)
	elif y == 1:
		s.append(t)
if min(len(f), len(s)) + len(both) < k:
	print(-1)
else:
	both = sorted(both)
	f = sorted(f)
	s = sorted(s)
	g = [both, f, s]
	for l in g:
		for (j, v) in enumerate(l):
			if j > 0:
				l[j] = l[j - 1] + l[j]
	if len(f) > len(s):
		b = f
		f = s
		s = b
	mn = 5 * 10 ** 9
	if len(f) == 0:
		mn = both[k - 1]
	for i in range(len(f) + 1):
		if i > k:
			break
		elif i > 0:
			if i == k:
				mn = min(f[i - 1] + s[i - 1], mn)
			elif len(both) >= k - i:
				mn = min(f[i - 1] + s[i - 1] + both[k - i - 1], mn)
		elif i == 0:
			if len(both) >= k:
				mn = both[k - 1]
	print(mn)


from collections import deque
(n, k) = map(int, input().split())
(s, s1, s2) = (deque(), deque(), deque())
for i in range(n):
	(a, b, c) = map(int, input().split())
	if b == 1 and c == 1:
		s.append(a)
	elif b == 1 and c == 0:
		s1.append(a)
	elif b == 0 and c == 1:
		s2.append(a)
(x, y) = (0, 0)
sum = 0
s1 = deque(sorted(s1))
s2 = deque(sorted(s2))
s = deque(sorted(s))
while len(s) != 0 and len(s1) != 0 and (len(s2) != 0):
	if x == k or y == k:
		break
	if s[0] <= s1[0] + s2[0]:
		sum = sum + s.popleft()
	else:
		sum = sum + s1.popleft()
		sum = sum + s2.popleft()
	x += 1
	y += 1
if x != k and y != k and (len(s1) == 0):
	while x != k and y != k and (len(s) != 0):
		sum = sum + s.popleft()
		x += 1
		y += 1
if x != k and y != k and (len(s2) == 0):
	while x != k and y != k and (len(s) != 0):
		sum = sum + s.popleft()
		y += 1
		x += 1
if x != k:
	while len(s1) != 0 and x != k:
		sum = sum + s1.popleft()
		x += 1
if y != k:
	while len(s2) != 0 and y != k:
		sum = sum + s2.popleft()
		y += 1
if x == k and y == k:
	print(sum)
else:
	print(-1)


(n, k) = list(map(int, input().split()))
arr1 = []
arr2 = []
arr3 = []
x = 0
y = 0
for i in range(n):
	num1 = list(map(int, input().split()))
	if num1[1] == 1 and num1[2] == 1:
		arr3.append(num1[0])
		x += 1
		y += 1
	elif num1[1] == 1 and num1[2] == 0:
		arr1.append(num1[0])
		x += 1
	elif num1[1] == 0 and num1[2] == 1:
		arr2.append(num1[0])
		y += 1
if x < k or y < k:
	print(-1)
else:
	arr1.sort()
	arr2.sort()
	a = len(arr1)
	b = len(arr2)
	for i in range(min(a, b)):
		arr3.append(arr1[i] + arr2[i])
	arr3.sort()
	ans = 0
	for i in range(k):
		ans += arr3[i]
	print(ans)


from math import inf
from queue import Queue
(n, k) = [int(_) for _ in input().split()]
books = [tuple((int(_) for _ in input().split())) for __ in range(n)]
if sum((_[1] for _ in books)) < k or sum((_[2] for _ in books)) < k:
	print(-1)
else:
	mem = {}
	books = sorted(books)
	alice_times = []
	bob_times = []
	both_times = []
	for (t, a, b) in books:
		if a and b:
			both_times.append(t)
		elif a:
			alice_times.append(t)
		elif b:
			bob_times.append(t)
	bob_times.append(inf)
	alice_times.append(inf)
	both_times.append(inf)
	t = 0
	i = j = l = 0
	alice_k = bob_k = 0
	while alice_k < k or bob_k < k:
		if both_times[l] < alice_times[i] + bob_times[j]:
			t += both_times[l]
			alice_k += 1
			bob_k += 1
			l += 1
		else:
			t += alice_times[i] + bob_times[j]
			i += 1
			j += 1
			alice_k += 1
			bob_k += 1
	print(t)


(n, k) = map(int, input().split())
ali = list()
bob = list()
both = list()
for i in range(n):
	l = list(map(int, input().split()))
	if l[1] == 1 and l[2] == 1:
		both.append(l[0])
	elif l[1] == 1:
		ali.append(l[0])
	elif l[2] == 1:
		bob.append(l[0])
ali.sort(reverse=True)
bob.sort(reverse=True)
both.sort(reverse=True)
a = len(ali)
b = len(bob)
if a > b:
	a = b
bt = len(both)
if a + bt < k:
	print(-1)
else:
	count = 0
	(i, j) = (-1, -1)
	(a, bt) = (-a, -bt)
	while i >= a and j >= bt and (k > 0):
		if ali[i] + bob[i] < both[j]:
			count += ali[i] + bob[i]
			k -= 1
			i -= 1
		else:
			count += both[j]
			j -= 1
			k -= 1
	if j < bt:
		while i >= a and k > 0:
			count += ali[i] + bob[i]
			k -= 1
			i -= 1
	else:
		while j >= bt and k > 0:
			count += both[j]
			j -= 1
			k -= 1
	print(count)


production = True
import sys, math, collections

def input(input_format=0, multi=0):
	if multi > 0:
		return [input(input_format) for i in range(multi)]
	else:
		next_line = sys.stdin.readline()[:-1]
		if input_format >= 10:
			use_list = False
			input_format = int(str(input_format)[-1])
		else:
			use_list = True
		if input_format == 0:
			formatted_input = [next_line]
		elif input_format == 1:
			formatted_input = list(map(int, next_line.split()))
		elif input_format == 2:
			formatted_input = list(map(float, next_line.split()))
		elif input_format == 3:
			formatted_input = list(next_line)
		elif input_format == 4:
			formatted_input = (lambda x: [x[0], list(map(int, x[1:]))])(next_line.split())
		elif input_format == 5:
			formatted_input = (lambda x: [x[0], list(map(float, x[1:]))])(next_line.split())
		elif input_format == 6:
			formatted_input = next_line.split()
		else:
			formatted_input = [next_line]
		return formatted_input if use_list else formatted_input[0]

def out(output_line, output_format=0, newline=True):
	formatted_output = ''
	if output_format == 0:
		formatted_output = str(output_line)
	elif output_format == 1:
		formatted_output = ' '.join(map(str, output_line))
	elif output_format == 2:
		formatted_output = '\n'.join(map(str, output_line))
	print(formatted_output, end='\n' if newline else '')

def log(*args):
	if not production:
		print('$$$', end='')
		print(*args)
enum = enumerate

def solve():
	(n, k) = input(1)
	y = input(1, n)
	a = []
	b = []
	c = []
	t = 0
	r = 0
	for (i, j, l) in y:
		if l and j:
			c.append(i)
		elif j:
			a.append(i)
		elif l:
			b.append(i)
	a.sort(reverse=True)
	b.sort(reverse=True)
	c.sort(reverse=True)
	while r < k:
		if not c and (not (a and b)):
			out(-1)
			break
		u = a[-1] + b[-1] if a and b else 10 ** 10
		o = c[-1] if c else 10 ** 10
		if u < o:
			t += a.pop() + b.pop()
		else:
			t += c.pop()
		r += 1
	else:
		out(t)
	return
solve()


(n, k) = [int(i) for i in input().split()]
books = [[int(i) for i in input().split()] for i in range(n)]
b01 = []
b10 = []
b11 = []
(b00c, b01c, b10c, b11c) = (0, 0, 0, 0)
index = 0
for book in books:
	if book[1] == 1:
		if book[2] == 1:
			b11.append(book[0])
		else:
			b10.append(book[0])
	elif book[2] == 1:
		b01.append(book[0])
(b11.sort(), b10.sort(), b01.sort())
b0_index = 0
b1_index = 0
time = 0
if len(b11) > 0:
	b1Out = False
else:
	b1Out = True
if len(b01) > 0 and len(b10) > 0:
	b0Out = False
else:
	b0Out = True
while b0_index + b1_index < k:
	if not any([b1Out, b0Out]):
		if b11[b1_index] < b01[b0_index] + b10[b0_index]:
			time += b11[b1_index]
			b1_index += 1
			if b1_index > len(b11) - 1:
				b1Out = True
		else:
			time += b01[b0_index] + b10[b0_index]
			b0_index += 1
			if b0_index > len(b01) - 1 or b0_index > len(b10) - 1:
				b0Out = True
	elif b1Out and b0Out:
		time = -1
		break
	elif b1Out:
		time += b01[b0_index] + b10[b0_index]
		b0_index += 1
		if b0_index == len(b01) or b0_index == len(b10):
			b0Out = True
	else:
		time += b11[b1_index]
		b1_index += 1
		if b1_index == len(b11):
			b1Out = True
print(time)


t = 1
while t > 0:
	(n, k) = map(int, input().split())
	a = []
	b = []
	c = []
	ans = 0
	for i in range(n):
		(ti, al, bo) = map(int, input().split())
		if al == 1 and bo == 1:
			c.append(ti)
		elif al == 1:
			a.append(ti)
		elif bo == 1:
			b.append(ti)
	a.sort()
	b.sort()
	for i in range(min(len(a), len(b))):
		c.append(a[i] + b[i])
	c.sort()
	if len(c) < k:
		print(-1)
	else:
		print(sum(c[:k]))
	t -= 1


import sys
from operator import itemgetter

def rl():
	return sys.stdin.readline().strip()
(n, k) = map(int, rl().split())
booksboth = []
booksalice = []
booksbob = []
for _ in range(n):
	nb = [int(x) for x in rl().split()]
	if nb[1] == 1 and nb[2] == 1:
		booksboth.append(nb)
	elif nb[1] == 1:
		booksalice.append(nb)
	elif nb[2] == 1:
		booksbob.append(nb)
booksalice = sorted(booksalice, key=itemgetter(0))
booksbob = sorted(booksbob, key=itemgetter(0))
a = len(booksalice)
b = len(booksbob)
for i in range(min(a, b)):
	booksboth.append([booksalice[i][x] + booksbob[i][x] for x in range(3)])
booksboth = sorted(booksboth, key=itemgetter(0))
if len(booksboth) < k:
	print(-1)
else:
	tot = 0
	for i in range(k):
		tot += booksboth[i][0]
	print(tot)


(a, k) = map(int, input().split())
l1 = []
l2 = []
l3 = []
for i in range(a):
	(b, c, d) = map(int, input().split())
	if c == 1 and d == 1:
		l3.append(b)
	elif c == 1:
		l1.append(b)
	elif d == 1:
		l2.append(b)
l1 = sorted(l1)
l2 = sorted(l2)
l3 = sorted(l3)
if len(l1) + len(l3) < k or len(l2) + len(l3) < k:
	print(-1)
else:
	d = 0
	k1 = 0
	k2 = 0
	k3 = 0
	for i in range(k):
		if len(l3) > k3 and (len(l1) > k1 and len(l2) > k2):
			if l3[k3] < l1[k1] + l2[k2]:
				d += l3[k3]
				k3 += 1
			else:
				d += l1[k1] + l2[k2]
				k1 += 1
				k2 += 1
		elif k3 < len(l3):
			d += l3[k3]
			k3 += 1
		else:
			d += l1[k1] + l2[k2]
			k1 += 1
			k2 += 1
	print(d)


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
(s1, s2, s3) = ([], [], [])
for i in range(n):
	(a, b, c) = map(int, input().split())
	if b == c == 1:
		s1.append(a)
	elif b == 1:
		s2.append(a)
	elif c == 1:
		s3.append(a)
s1.sort()
s2.sort()
s3.sort()
(i, j, l) = (0, 0, 0)
days = 0
likes = 0
(n1, n2, n3) = (len(s1), len(s2), len(s3))
while likes < k:
	if i == n1:
		if j == n2 or l == n3:
			break
		likes += 1
		days += s2[j] + s3[l]
		j += 1
		l += 1
	elif j == n2:
		if i == n1:
			break
		likes += 1
		days += s1[i]
		i += 1
	elif l == n3:
		if i == n1:
			break
		likes += 1
		days += s1[i]
		i += 1
	elif s1[i] >= s2[j] + s3[l]:
		days += s2[j] + s3[l]
		j += 1
		l += 1
		likes += 1
	else:
		days += s1[i]
		i += 1
		likes += 1
	if i == n1 and j == n2 and (l == n3):
		break
if likes < k:
	print(-1)
else:
	print(days)


(t, k) = map(int, input().split())
arra = []
arrb = []
arrc = []
ans = 0
for i in range(t):
	(a, b, c) = map(int, input().split())
	if b == c == 1:
		arra.append(a)
	elif b == 0 and c == 1:
		arrc.append(a)
	elif b == 1 and c == 0:
		arrb.append(a)
arra.sort()
arrb.sort()
arrc.sort()
(l1, l2, l3) = (len(arra), len(arrb), len(arrc))
if min(l2, l3) < k and k - min(l2, l3) > l1:
	print(-1)
else:
	x = k
	y = k
	index = 0
	curr = 0
	while x != 0 or y != 0:
		s1 = 0
		Flag = True
		if curr < l2:
			s1 += arrb[curr]
		else:
			Flag = False
		if curr < l3:
			s1 += arrc[curr]
		else:
			Flag = False
		if index < l1 and s1 > arra[index] or Flag == False:
			ans += arra[index]
			index += 1
			x -= 1
			y -= 1
		else:
			ans += arrb[curr]
			ans += arrc[curr]
			curr += 1
			x -= 1
			y -= 1
	print(ans)


(n, k) = map(int, input().split())
a = []
b = []
ab = []
for i in range(n):
	(x, y, z) = map(int, input().split())
	if y == 1 and z == 1:
		ab.append(x)
	elif y == 1:
		a.append(x)
	elif z == 1:
		b.append(x)
a = sorted(a)
b = sorted(b)
for i in range(min(len(a), len(b))):
	ab.append(a[i] + b[i])
ab = sorted(ab)
ans = 0
if len(ab) >= k:
	for i in range(k):
		ans += ab[i]
else:
	print(-1)
	exit()
print(ans)


from collections import deque
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from bisect import bisect_left as bl
from math import log2, ceil
from itertools import permutations

def main():
	(n, k) = [int(j) for j in input().split()]
	l = []
	for i in range(n):
		l.append([int(j) for j in input().split()])
	l.sort()
	al = []
	bl = []
	both = []
	for i in range(n):
		if l[i][1] == 1 and l[i][2] == 1:
			both.append(i)
		elif l[i][1]:
			al.append(i)
		elif l[i][2]:
			bl.append(i)
	a = 0
	b = 0
	c = 0
	ans = 0
	i = k
	j = k
	while a < len(al) and b < len(bl) and (c < len(both)) and (i > 0) and (j > 0):
		if l[al[a]][0] < l[both[c]][0] and l[bl[b]][0] < l[both[c]][0] and (l[al[a]][0] + l[bl[b]][0] < l[both[c]][0]):
			ans += l[al[a]][0] + l[bl[b]][0]
			a += 1
			b += 1
		else:
			ans += l[both[c]][0]
			c += 1
		i -= 1
		j -= 1
	if i > 0:
		while c < len(both) and i > 0:
			ans += l[both[c]][0]
			c += 1
			i -= 1
			j -= 1
		while a < len(al) and i > 0:
			ans += l[al[a]][0]
			a += 1
			i -= 1
	if j > 0:
		while c < len(both) and j > 0:
			ans += l[both[c]][0]
			c += 1
			j -= 1
			i -= 1
		while b < len(bl) and j > 0:
			ans += l[bl[b]][0]
			b += 1
			j -= 1
	if i > 0 or j > 0:
		print(-1)
	else:
		print(ans)
main()


(n, k) = [int(x) for x in input().split()]
at = []
bt = []
ct = []
for i in range(n):
	(ti, ai, bi) = [int(x) for x in input().split()]
	if ai == 1 and bi == 1:
		ct.append(ti)
	elif ai == 1:
		at.append(ti)
	elif bi == 1:
		bt.append(ti)
	else:
		continue
if len(ct) + len(at) < k or len(ct) + len(bt) < k:
	print(-1)
else:
	ci = 0
	ai = 0
	al = k
	ans = 0
	ct.sort()
	at.sort()
	bt.sort()
	i = 0
	while i < len(ct) and al > 0 and (ai < min(len(at), len(bt))):
		if ct[i] < at[ai] + bt[ai]:
			ans += ct[i]
			i += 1
		else:
			ans += at[ai] + bt[ai]
			ai += 1
		al -= 1
	if i == len(ct) and al != 0:
		bl = al
		ans += sum(at[ai:ai + al]) + sum(bt[ai:ai + al])
	elif ai == min(len(at), len(bt)) and al > 0:
		ans += sum(ct[i:i + al])
	print(ans)


(n, k) = map(int, input().split(' '))
book = [[] for i in range(4)]
s = [[] for i in range(4)]
for i in range(n):
	(t, a, b) = map(int, input().split(' '))
	book[2 * a + b].append(t)
for i in range(1, 4):
	book[i].sort()
	s[i].append(0)
	for j in book[i]:
		s[i].append(s[i][len(s[i]) - 1] + j)
ans = int(2000000000.0 + 1)
for i in range(min(k + 1, len(s[3]))):
	if k - i < len(s[1]) and k - i < len(s[2]):
		ans = min(ans, s[3][i] + s[1][k - i] + s[2][k - i])
print(-1 if ans == int(2000000000.0 + 1) else ans)


(n, k) = map(int, input().split())
cnta = []
cntb = []
cntab = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a:
		if b:
			cntab.append(t)
		else:
			cnta.append(t)
	elif b:
		cntb.append(t)
T = 0
cnta = sorted(cnta)
cntb = sorted(cntb)
cntab = sorted(cntab)
(l, m) = (0, 0)
r = min(len(cnta), len(cntb))
it = 0
while l < r and it < k:
	if m >= len(cntab) or cnta[l] + cntb[l] < cntab[m]:
		T += cnta[l] + cntb[l]
		l += 1
	else:
		T += cntab[m]
		m += 1
	it += 1
if it + len(cntab) - m < k:
	print(-1)
else:
	print(T + sum(cntab[m:m + k - it]))


from sys import stdin, stdout

def input():
	return stdin.readline().strip()
(N, K) = input().split(' ')
N = int(N)
K = int(K)
alice_only = []
bob_only = []
both = []
for _ in range(N):
	(t, a, b) = input().split(' ')
	t = int(t)
	a = int(a)
	b = int(b)
	if a == 0 and b == 0:
		continue
	if a == 1 and b == 1:
		both += [t]
	if a == 1 and b == 0:
		alice_only += [t]
	if a == 0 and b == 1:
		bob_only += [t]
hybrid = []
alice_only = sorted(alice_only)
bob_only = sorted(bob_only)
for (a, b) in zip(alice_only, bob_only):
	hybrid += [a + b]
candidates = sorted(both + hybrid)
if len(candidates) < K:
	print(-1)
else:
	print(sum(candidates[0:K]))


(n, k) = map(int, input().split())
books = []
alice = []
bob = []
for _ in range(n):
	book = tuple(map(int, input().split()))
	if book[1] == book[2] == 1:
		books.append(book[0])
	elif book[1] == 1:
		alice.append(book[0])
	elif book[2] == 1:
		bob.append(book[0])
for (a, b) in zip(sorted(alice), sorted(bob)):
	books.append(a + b)
print(sum(sorted(books)[:k]) if len(books) >= k else -1)


from sys import stdin, stdout
import math
from collections import defaultdict, deque
(n, k) = map(int, stdin.readline().split())
(al, bl, both) = ([], [], [])
for _ in range(n):
	(t, a, b) = map(int, stdin.readline().split())
	if a == 0 and b == 0:
		continue
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1:
		al.append(t)
	elif b == 1:
		bl.append(t)
(al, bl, both) = (deque(sorted(al)[:k]), deque(sorted(bl)[:k]), deque(sorted(both)[:k]))
(res, cnt) = (0, 0)
while cnt < k:
	if both:
		if al and bl:
			if both[0] < al[0] + bl[0]:
				res += both[0]
				both.popleft()
				cnt += 1
			else:
				res += al[0] + bl[0]
				al.popleft()
				bl.popleft()
				cnt += 1
		else:
			res += both[0]
			both.popleft()
			cnt += 1
	elif al and bl:
		res += al[0] + bl[0]
		al.popleft()
		bl.popleft()
		cnt += 1
	else:
		res = -1
		break
print(res)


(n, k) = map(int, input().split())
a = b = c = 0
m = []
m1 = []
m2 = []
for i in range(n):
	(a, b, c) = map(int, input().split())
	if b == c == 1:
		m.append(a)
	elif b > c:
		m1.append(a)
	elif b < c:
		m2.append(a)
m.sort()
m1.sort()
m2.sort()
for i in range(min(len(m1), len(m2))):
	m.append(m1[i] + m2[i])
m.sort()
if len(m) < k:
	print(-1)
else:
	print(sum(m[:k]))


from sys import stdin
input = stdin.readline

def p(x):
	return x[0]
(n, k) = map(int, input().split())
a = []
for i in range(n):
	a.append(list(map(int, input().split())))
a.sort(key=p)
(alice, bob, common) = ([], [], [])
(al, bo) = (0, 0)
for i in a:
	if i[1] and (not i[2]) and (al < k):
		alice.append(i[0])
		al += 1
	if i[2] and (not i[1]) and (bo < k):
		bob.append(i[0])
		bo += 1
	if i[1] and i[2]:
		if al < k or bo < k:
			common.append(i[0])
			al += 1
			bo += 1
			if al > k:
				alice.pop()
				al -= 1
			if bo > k:
				bob.pop()
				bo -= 1
		elif alice and bob:
			if alice[-1] + bob[-1] > i[0]:
				alice.pop()
				bob.pop()
				common.append(i[0])
			else:
				break
if al >= k and bo >= k:
	print(sum(alice) + sum(bob) + sum(common))
else:
	print(-1)


(n, k) = map(int, input().split())
ab = []
a = []
b = []
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x == 1 and y == 1:
		ab.append(t)
	elif x == 1 and y != 1:
		a.append(t)
	elif x == 0 and y == 1:
		b.append(t)
a.sort()
b.sort()
cnt = min(len(a), len(b))
for i in range(cnt):
	ab.append(a[i] + b[i])
if len(ab) < k:
	print(-1)
else:
	ab = sorted(ab)
	print(sum(ab[:k]))


(n, k) = map(int, input().split())
ar11 = []
ar10 = []
ar01 = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		ar11.append(t)
	elif a == 1 and b == 0:
		ar10.append(t)
	elif a == 0 and b == 1:
		ar01.append(t)
if len(ar11) + min(len(ar10), len(ar01)) >= k:
	ar10.sort()
	ar01.sort()
	for i in range(min(len(ar10), len(ar01))):
		ar11.append(ar10[i] + ar01[i])
	ar11.sort()
	print(sum(ar11[:k]))
else:
	print('-1')


from __future__ import division, print_function
from sys import stdin, stdout
import bisect
import math
import heapq

def inin():
	return int(input())

def stin():
	return input()

def spin():
	return map(int, stin().split())

def lin():
	return list(map(int, stin().split()))

def matrix(n):
	return [list(map(int, input().split())) for i in range(n)]

def count2Dmatrix(i, list):
	return sum((c.count(i) for c in list))

def modinv(n, p):
	return pow(n, p - 2, p)

def GCD(x, y):
	x = abs(x)
	y = abs(y)
	if min(x, y) == 0:
		return max(x, y)
	while y:
		(x, y) = (y, x % y)
	return x

def Divisors(n):
	l = []
	for i in range(1, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
	return l
prime = []

def SieveOfEratosthenes(n):
	global prime
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	f = []
	for p in range(2, n):
		if prime[p]:
			f.append(p)
	return f
q = []

def dfs(n, d, v, c):
	global q
	v[n] = 1
	x = d[n]
	q.append(n)
	j = c
	for i in x:
		if i not in v:
			f = dfs(i, d, v, c + 1)
			j = max(j, f)
	return j
(n, k) = spin()
(alice, bob, both) = ([], [], [])
for _ in range(n):
	(t, a, b) = spin()
	if a & b:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
alice = sorted(alice)
bob = sorted(bob)
for i in range(min(len(alice), len(bob))):
	both.append(alice[i] + bob[i])
if len(both) >= k:
	print(sum(sorted(both)[:k]))
else:
	print(-1)


import sys, io, os, time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect, math, heapq
alphabet = 'abcdefghijklmnopqrstuvwxyz'
input = sys.stdin.readline
(n, k) = map(int, input().split())
both = []
alice = []
bob = []
for i in range(n):
	(x, y, z) = map(int, input().split())
	if y and z:
		both.append(x)
	elif y:
		alice.append(x)
	elif z:
		bob.append(x)
alice.sort()
bob.sort()
for i in range(min(len(alice), len(bob))):
	both.append(alice[i] + bob[i])
both.sort()
if len(both) < k:
	print(-1)
else:
	print(sum(both[:k]))


import sys
input = sys.stdin.readline
f = lambda : list(map(int, input().strip('\n').split()))
(n, k) = f()
_11 = []
_01 = []
_10 = []
for _ in range(n):
	(t, a, b) = f()
	if a and b:
		_11.append(t)
	elif a:
		_10.append(t)
	elif b:
		_01.append(t)
_01.sort()
_10.sort()
_11.sort()
for i in range(1, len(_01)):
	_01[i] += _01[i - 1]
for i in range(1, len(_10)):
	_10[i] += _10[i - 1]
for i in range(1, len(_11)):
	_11[i] += _11[i - 1]
ans = 3 * 1000000000.0
if len(_01) >= k and len(_10) >= k:
	ans = min(ans, _01[k - 1] + _10[k - 1])
for i in range(len(_11)):
	if i + 1 < k and len(_01) >= k - i - 1 and (len(_10) >= k - i - 1):
		ans = min(ans, _11[i] + _01[k - i - 2] + _10[k - i - 2])
	elif len(_11) >= k:
		ans = min(ans, _11[k - 1])
		break
print(-1 if ans == 3 * 1000000000.0 else ans)


(n, k) = map(int, input().split())
c = []
d = []
e = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 0:
		c.append(t)
	elif b == 1 and a == 0:
		d.append(t)
	elif a == 1 and b == 1:
		e.append(t)
if len(c) + len(e) < k or len(d) + len(e) < k:
	print(-1)
else:
	c = sorted(c)
	d = sorted(d)
	e = sorted(e)
	l1 = len(c)
	l2 = len(d)
	l3 = len(e)
	s = 0
	i1 = 0
	i2 = 0
	i3 = 0
	while i1 + i3 < k or i2 + i3 < k:
		if i3 < l3:
			if i2 + i3 >= k and i1 < l1:
				if e[i3] <= c[i1]:
					s += e[i3]
					i3 += 1
				else:
					s += c[i1]
					i1 += 1
			elif i1 + i3 >= k and i2 < l2:
				if e[i3] <= d[i2]:
					s += e[i3]
					i3 += 1
				else:
					s += d[i2]
					i2 += 1
			elif i1 < l1 and i2 < l2:
				if e[i3] <= c[i1] + d[i2]:
					s += e[i3]
					i3 += 1
				else:
					s += c[i1] + d[i2]
					i1 += 1
					i2 += 1
			else:
				s += e[i3]
				i3 += 1
		else:
			s += c[i1] + d[i2]
			i1 += 1
			i2 += 1
	print(s)


(n, k) = map(int, input().split())
ab = [0]
a = [0]
b = [0]
for i in range(n):
	(t, ai, bi) = map(int, input().split())
	if ai == 1 and bi == 1:
		ab.append(t)
	elif ai == 1:
		a.append(t)
	elif bi == 1:
		b.append(t)
if len(ab) - 1 + len(a) - 1 < k or len(ab) - 1 + len(b) - 1 < k:
	print(-1)
else:
	ab.sort()
	a.sort()
	b.sort()
	for j in range(len(ab) - 1):
		ab[j + 1] = ab[j] + ab[j + 1]
	for l in range(len(a) - 1):
		a[l + 1] = a[l] + a[l + 1]
	for m in range(len(b) - 1):
		b[m + 1] = b[m] + b[m + 1]
	ab_read = min(len(ab) - 1, k)
	a_read = max(k - ab_read, 0)
	b_read = max(k - ab_read, 0)
	ans = ab[ab_read] + a[a_read] + b[b_read]
	for x in range(min(ab_read, len(a) - a_read - 1, len(b) - b_read - 1)):
		ab_read -= 1
		a_read += 1
		b_read += 1
		check = ab[ab_read] + a[a_read] + b[b_read]
		if check < ans:
			ans = check
	print(ans)


(n, k) = map(int, input().split())
(la, lb, lc) = ([], [], [])
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == b == 1:
		lc.append(t)
	elif a == 1 and b == 0:
		la.append(t)
	elif a == 0 and b == 1:
		lb.append(t)
la.sort()
lb.sort()
lc.sort()
t = 0
ln = len(lc)
if ln >= k:
	t += sum(lc[:k])
	(a, b) = (k, k)
	ln = k
else:
	t += sum(lc)
	(a, b) = (ln, ln)
if a + len(la) < k or b + len(lb) < k:
	print(-1)
else:
	t += sum(la[:k - a]) + sum(lb[:k - b])
	(u, v) = (k - a, k - b)
	while u < len(la) and v < len(lb) and (ln > 0):
		if t - lc[ln - 1] + la[u] + lb[v] < t:
			t = t - lc[ln - 1] + la[u] + lb[v]
			u += 1
			v += 1
			ln -= 1
		else:
			break
	print(t)


from sys import stdin, stdout
from sys import maxsize
from functools import cmp_to_key

def solve(books, k):
	alice = []
	bob = []
	both = []
	for book in books:
		if book[1] == 1 and book[2] == 1:
			both.append(book[0])
		elif book[1] == 0 and book[2] == 1:
			bob.append(book[0])
		elif book[1] == 1 and book[2] == 0:
			alice.append(book[0])
	alice.sort(reverse=True)
	bob.sort(reverse=True)
	both.sort(reverse=True)
	(no_of_books, time) = (0, 0)
	while len(alice) != 0 and len(bob) != 0 and (len(both) != 0) and (no_of_books < k):
		no_of_books += 1
		if alice[-1] + bob[-1] < both[-1]:
			time += alice[-1] + bob[-1]
			alice.pop()
			bob.pop()
		else:
			time += both[-1]
			both.pop()
	while len(both) != 0 and no_of_books < k:
		no_of_books += 1
		time += both[-1]
		both.pop()
	while len(alice) != 0 and len(bob) != 0 and (no_of_books < k):
		no_of_books += 1
		time += alice[-1] + bob[-1]
		alice.pop()
		bob.pop()
	if no_of_books == k:
		return time
	else:
		return -1
test = 1
for t in range(0, test):
	(n, k) = list(map(int, input().split()))
	b = [tuple(map(int, input().split())) for i in range(n)]
	ans = solve(b, k)
	print(ans)


from sys import stdin
(n, k) = map(int, input().split())
x = []
y = []
z = []
k1 = 0
k2 = 0
for i in range(n):
	(t, a, b) = map(int, stdin.readline().split())
	if a == 1 and b == 1:
		x.append(t)
		k1 += 1
		k2 += 1
	elif a == 1:
		k1 += 1
		y.append(t)
	elif b == 1:
		k2 += 1
		z.append(t)
if k1 < k or k2 < k:
	print(-1)
else:
	x.sort()
	y.sort()
	z.sort()
	ans = 0
	k1 = 0
	k2 = 0
	p1 = 0
	p2 = 0
	p3 = 0
	lx = len(x)
	ly = len(y)
	lz = len(z)
	for i in range(k):
		if p1 >= lx:
			ans += y[p2] + z[p3]
			p2 += 1
			p3 += 1
		elif p2 >= ly or p3 >= lz:
			ans += x[p1]
			p1 += 1
		elif x[p1] <= y[p2] + z[p3]:
			ans += x[p1]
			p1 += 1
		else:
			ans += y[p2] + z[p3]
			p2 += 1
			p3 += 1
	print(ans)


class Books:

	def __init__(self, time, alice_like, bob_like):
		self.time = time
		self.alice_like = alice_like
		self.bob_like = bob_like

def solve():
	(n, k) = map(int, input().split())
	books = []
	for i in range(n):
		(t, a, b) = map(int, input().split())
		books.append(Books(t, a == 1, b == 1))
	books_everybody_like = []
	books_alice_like = []
	books_bob_like = []
	for b in books:
		if b.alice_like and b.bob_like:
			books_everybody_like.append(b)
		elif b.alice_like:
			books_alice_like.append(b)
		elif b.bob_like:
			books_bob_like.append(b)
	books_alice_like = sorted(books_alice_like, key=lambda x: x.time)
	books_bob_like = sorted(books_bob_like, key=lambda x: x.time)
	for (a, b) in zip(books_alice_like, books_bob_like):
		books_everybody_like.append(Books(a.time + b.time, True, True))
	if len(books_everybody_like) < k:
		print(-1)
		return
	books_everybody_like = sorted(books_everybody_like, key=lambda x: x.time)
	answer = 0
	for i in range(k):
		answer += books_everybody_like[i].time
	print(answer)
solve()


(n, k) = map(int, input().split())
doubles = []
single_a = []
single_b = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == b:
		if a == 1:
			doubles.append(t)
	else:
		if a:
			single_a.append([t, a, b])
		if b:
			single_b.append([t, a, b])
single_a.sort(key=lambda x: x[0])
single_b.sort(key=lambda x: x[0])
for i in range(min(len(single_a), len(single_b))):
	ta = single_a[i][0]
	tb = single_b[i][0]
	doubles.append(ta + tb)
doubles.sort()
time = 0
if len(doubles) < k:
	time = -1
else:
	time = sum(doubles[:k])
print(time)


(n, k) = map(int, input().split())
alice = []
bob = []
both = []
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		both.append((t, a, b))
	elif a == 1 and b == 0:
		alice.append((t, a, b))
	elif a == 0 and b == 1:
		bob.append((t, a, b))
alice.sort()
bob.sort()
both.sort()
ans = 0
ca = 0
cb = 0
ia = 0
ib = 0
iboth = 0
while ca < k and cb < k and (ia < len(alice) and ib < len(bob) or iboth < len(both)):
	if iboth >= len(both) or (ia < len(alice) and ib < len(bob) and (alice[ia][0] + bob[ib][0] < both[iboth][0])):
		ans += alice[ia][0] + bob[ib][0]
		ia += 1
		ib += 1
	else:
		ans += both[iboth][0]
		iboth += 1
	ca += 1
	cb += 1
if cb >= k and ca >= k:
	print(ans)
else:
	print(-1)


import sys
tokens = input().split()
(n, nb_required) = (int(tokens[0]), int(tokens[1]))
both_liked = []
alice_liked = []
bob_liked = []
for i in range(n):
	tokens = input().split()
	(t, a, b) = (int(tokens[0]), int(tokens[1]), int(tokens[2]))
	if a == 1 and b == 1:
		both_liked.append(t)
	elif a == 1:
		alice_liked.append(t)
	elif b == 1:
		bob_liked.append(t)
both_liked.sort()
alice_liked.sort()
bob_liked.sort()
i = 0
j = 0
k = 0
total = 0
while nb_required > 0:
	if k < len(both_liked):
		if i == len(alice_liked) or j == len(bob_liked) or both_liked[k] <= alice_liked[i] + bob_liked[j]:
			nb_required -= 1
			total += both_liked[k]
			k += 1
			continue
	if i == len(alice_liked) or j == len(bob_liked):
		print(-1)
		sys.exit(0)
	nb_required -= 1
	total += alice_liked[i] + bob_liked[j]
	i += 1
	j += 1
print(total)


from heapq import heappush, heappop
import math as m
(n, k) = map(int, input().split())
a_b = []
b_b = []
ab_b = []
for book in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		heappush(ab_b, t)
	elif a == 1:
		heappush(a_b, t)
	elif b == 1:
		heappush(b_b, t)
a_like = 0
b_like = 0
result = 0
while True:
	if a_like < k and b_like < k:
		if len(ab_b) == 0:
			if len(a_b) == 0:
				print(-1)
				exit()
			else:
				result += heappop(a_b)
				a_like += 1
			if len(b_b) == 0:
				print(-1)
				exit()
			else:
				result += heappop(b_b)
				b_like += 1
		else:
			anext = a_b[0] if len(a_b) > 0 else m.inf
			bnext = b_b[0] if len(b_b) > 0 else m.inf
			if anext + bnext < ab_b[0]:
				result += heappop(a_b)
				a_like += 1
				result += heappop(b_b)
				b_like += 1
			else:
				result += heappop(ab_b)
				a_like += 1
				b_like += 1
	elif a_like < k:
		if len(ab_b) == 0 and len(a_b) == 0:
			print(-1)
			exit()
		elif len(ab_b) == 0:
			result += heappop(a_b)
		elif len(a_b) == 0:
			result += heappop(ab_b)
		elif a_b[0] < ab_b[0]:
			result += heappop(a_b)
		else:
			result += heappop(ab_b)
	elif b_like < k:
		if len(ab_b) == 0 and len(b_b) == 0:
			print(-1)
			exit()
		elif len(ab_b) == 0:
			result += heappop(b_b)
		elif len(b_b) == 0:
			result += heappop(ab_b)
		elif b_b[0] < ab_b[0]:
			result += heappop(b_b)
		else:
			result += heappop(ab_b)
	else:
		break
print(result)


(n, k) = list(map(int, input().split()))
times = [[], [], [], []]
for _ in range(n):
	(t, a, b) = list(map(int, input().split()))
	times[2 * a + b].append(t)
for i in range(1, 4):
	times[i] = sorted(times[i][:])
prefix_sums = [[], [], [], []]
for i in range(1, 4):
	prefix_sums[i].append(0)
	for v in times[i]:
		prefix_sums[i].append(prefix_sums[i][-1] + v)
mint = 2000000000.0 + 1
for i in range(min(k + 1, len(prefix_sums[3]))):
	needs = k - i
	if len(prefix_sums[1]) > needs and len(prefix_sums[2]) > needs:
		mint = min(mint, prefix_sums[3][i] + prefix_sums[1][needs] + prefix_sums[2][needs])
if mint == 2000000000.0 + 1:
	mint = -1
print(mint)


import sys
input = sys.stdin.readline
(a, b) = list(map(int, input().split()))
AL = []
A = []
B = []
for _ in range(a):
	n = list(map(int, input().split()))
	if n[1] == 1 and n[2] == 1:
		AL.append(n[0])
	elif n[1] == 1 and n[2] == 0:
		A.append(n[0])
	elif n[1] == 0 and n[2] == 1:
		B.append(n[0])
A.sort()
B.sort()
for k in range(min(len(A), len(B))):
	AL.append(A[k] + B[k])
if len(AL) < b:
	print(-1)
else:
	AL.sort()
	ans = sum(AL[:b])
	print(ans)


from sys import stdout
from collections import defaultdict
import math
(n, k) = map(int, input().split())
l = list()
d = defaultdict(list)
for i in range(n):
	(a, b, c) = map(int, input().split())
	s = str(b) + str(c)
	d[s].append(a)
l1 = sorted(d['11'])
l2 = sorted(d['10'])
l3 = sorted(d['01'])
ans = 0
l4 = list()
m = min(len(l2), len(l3))
for i in range(m):
	l4.append(l2[i] + l3[i])
l = sorted(l1 + l4)
if len(l) < k:
	stdout.write(str(-1) + '\n')
else:
	print(sum(l[:k]))


(n, k) = map(int, input().split(' '))
both = []
bob = []
alice = []
for i in range(n):
	(t, a, b) = map(int, input().split(' '))
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
if len(both) != 0:
	both.sort()
if len(alice) != 0:
	alice.sort()
if len(bob) != 0:
	bob.sort()
if len(both) + len(alice) < k or len(both) + len(bob) < k:
	print(-1)
else:
	i = 0
	j = 0
	ans = 0
	q = 0
	w = 0
	talice = 0
	tbob = 0
	while i < len(alice) and j < len(bob) and (q < k) and (w < len(both)):
		if alice[i] + bob[j] <= both[w]:
			ans += alice[i] + bob[j]
			talice += 1
			tbob += 1
			i += 1
			j += 1
		else:
			ans += both[w]
			talice += 1
			tbob += 1
			w += 1
		q += 1
	z = talice
	if i == len(alice) or j == len(bob):
		ans += sum(both[w:w + k - z])
	elif w == len(both):
		ans += sum(alice[i:i + k - z])
		ans += sum(bob[j:j + k - z])
	print(ans)


from collections import defaultdict
(n, k) = list(map(int, input().split()))
arr = []
for i in range(n):
	temp = list(map(int, input().split()))
	arr.append(temp)
d = defaultdict(list)
for i in range(len(arr)):
	(ti, ai, bi) = arr[i]
	if ai == 1 and bi == 1:
		if '11' in d.keys():
			d['11'].append(ti)
		else:
			d['11'] = [ti]
	elif ai == 0 and bi == 1:
		if '01' in d.keys():
			d['01'].append(ti)
		else:
			d['01'] = [ti]
	elif ai == 1 and bi == 0:
		if '10' in d.keys():
			d['10'].append(ti)
		else:
			d['10'] = [ti]
smallest_one = min(len(d['01']), len(d['10']))
two = len(d['11'])
for i in d.keys():
	d[i] = sorted(d[i])
ans = 0
l1 = 0
l2 = 0
current_k = 0
while l1 < two and l2 < smallest_one and (current_k < k):
	if d['11'][l1] <= d['01'][l2] + d['10'][l2]:
		ans += d['11'][l1]
		l1 += 1
	else:
		ans += d['01'][l2] + d['10'][l2]
		l2 += 1
	current_k += 1
if current_k != k and l1 < two:
	while l1 < two and current_k < k:
		ans += d['11'][l1]
		l1 += 1
		current_k += 1
elif current_k != k and l2 < smallest_one:
	while l2 < smallest_one and current_k < k:
		ans += d['01'][l2] + d['10'][l2]
		l2 += 1
		current_k += 1
if current_k == k:
	print(ans)
else:
	print(-1)


from collections import deque
from sys import stdin, stdout
(n, k) = list(map(int, input().split()))
p = []
al = 0
bob = 0
ali = []
c = []
bobi = []
for i in range(n):
	(t, a, b) = list(map(int, stdin.readline().split()))
	p.append((t, a, b))
	if a == 1:
		al += 1
	if b == 1:
		bob += 1
	if a == 1 and b == 0:
		ali.append(t)
	if a == 0 and b == 1:
		bobi.append(t)
	if a == 1 and b == 1:
		c.append(t)
if al < k or bob < k:
	print(-1)
	exit()
ali.sort()
c.sort()
bobi.sort()
ali = deque(ali)
bobi = deque(bobi)
c = deque(c)
ans = 0
for i in range(k):
	if len(c) > 0:
		if len(ali) > 0 and len(bobi) > 0:
			if ali[0] + bobi[0] <= c[0]:
				ans += ali[0] + bobi[0]
				ali.popleft()
				bobi.popleft()
			else:
				ans += c[0]
				c.popleft()
		else:
			ans += c[0]
			c.popleft()
	else:
		ans += ali[0]
		ans += bobi[0]
		ali.popleft()
		bobi.popleft()
print(ans)


(n, k) = map(int, input().split())
alice = list()
bob = list()
both = list()
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1:
		if b == 1:
			both.append(t)
		else:
			alice.append(t)
	elif b == 1:
		bob.append(t)
alice = sorted(alice)
bob = sorted(bob)
both = sorted(both)
final = list()
for i in range(min(len(alice), len(bob))):
	final.append(alice[i] + bob[i])
fp = 0
bp = 0
time = 0
count = 0
while count < k:
	if fp + 1 > len(final) and bp + 1 > len(both):
		break
	elif fp + 1 > len(final):
		time += both[bp]
		count += 1
		bp += 1
	elif bp + 1 > len(both):
		time += final[fp]
		count += 1
		fp += 1
	elif final[fp] <= both[bp]:
		time += final[fp]
		count += 1
		fp += 1
	else:
		time += both[bp]
		count += 1
		bp += 1
if count >= k:
	print(time)
else:
	print(-1)


(n, k) = map(int, input().split())
x = list()
y = list()
z = list()
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == 0 and b == 0:
		continue
	elif a == 1 and b == 0:
		x.append(t)
	elif a == 0 and b == 1:
		y.append(t)
	else:
		z.append(t)
x.sort()
y.sort()
for i in range(min(len(x), len(y))):
	z.append(x[i] + y[i])
z.sort()
if len(z) < k:
	print('-1')
else:
	res = 0
	for i in range(0, k):
		res += z[i]
	print(res)


from sys import stdin
input = lambda : stdin.readline().strip()
char = [chr(i) for i in range(97, 123)]
CHAR = [chr(i) for i in range(65, 91)]
mp = lambda : list(map(int, input().split()))
INT = lambda : int(input())
rn = lambda : range(INT())
from math import ceil, sqrt, factorial, gcd
(n, k) = mp()
alice = []
bob = []
common = []
for i in range(n):
	(t, a, b) = mp()
	if a == b == 1:
		common.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
if len(common + alice) < k or len(common + bob) < k:
	print(-1)
elif (len(alice) == 0 or len(bob) == 0) and len(common) >= k:
	common.sort()
	print(sum(common[:k]))
else:
	alice.sort()
	bob.sort()
	common.sort()
	inx = min(k, len(alice), len(bob))
	sma = sum(alice[:inx])
	smb = sum(bob[:inx])
	res = sma + smb
	if inx < k:
		res += sum(common[:k - inx])
	common_inx = k - inx
	inx = inx
	res1 = res
	while common_inx < len(common) and inx > 0:
		res -= alice[inx - 1]
		res -= bob[inx - 1]
		res += common[common_inx]
		res1 = min(res, res1)
		inx -= 1
		common_inx += 1
	print(res1)


import sys
import math
import collections
import heapq

def set_debug(debug_mode=False):
	if debug_mode:
		fin = open('input.txt', 'r')
		sys.stdin = fin

def int_input():
	return list(map(int, input().split()))
t = 1
for ti in range(1, t + 1):
	(n, k) = int_input()
	both = []
	Ab = []
	Bb = []
	A = 0
	B = 0
	for _ in range(n):
		(t, a, b) = int_input()
		if a == 1 and b == 1:
			both.append(t)
		elif a == 1:
			Ab.append(t)
		elif b == 1:
			Bb.append(t)
	Ab.sort()
	Bb.sort()
	for i in range(min(len(Ab), len(Bb))):
		both.append(Ab[i] + Bb[i])
	print(-1 if len(both) < k else sum(sorted(both)[:k]))


(a, b) = map(int, input().split())
(m, n, o, ans) = ([], [], [], 0)
for _ in range(a):
	(q, w, e) = map(int, input().split())
	if w == e == 1:
		m.append(q)
	elif w != e:
		if e == 0:
			n.append(q)
		else:
			o.append(q)
m.sort()
n.sort()
o.sort()
(v, t, u) = ([], min(len(n), len(o)), len(m))
for i in range(t):
	v.append(n[i] + o[i])
if b > u + t:
	print(-1)
else:
	(i, j) = (0, 0)
	while b > 0:
		if i < u and j < t:
			if m[i] <= v[j]:
				ans += m[i]
				i += 1
			else:
				ans += v[j]
				j += 1
		elif i <= u - 1:
			ans += m[i]
			i += 1
		elif j <= t - 1:
			ans += v[j]
			j += 1
		b -= 1
	print(ans)


(n, k) = map(int, input().split())
A = []
B = []
AB = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 0:
		A.append(t)
	if b == 1 and a == 0:
		B.append(t)
	if a == 1 and b == 1:
		AB.append(t)
A.sort()
B.sort()
AB.sort()
ia = 0
ib = 0
iab = 0
kab = 0
total_time = 0
while True:
	if iab > len(AB) - 1 and (ia > len(A) - 1 or ib > len(B) - 1):
		print(-1)
		break
	if iab <= len(AB) - 1:
		if ia > len(A) - 1 or ib > len(B) - 1:
			total_time += AB[iab]
			kab += 1
			if kab == k:
				print(total_time)
				break
			iab += 1
		elif AB[iab] < A[ia] + B[ib]:
			total_time += AB[iab]
			kab += 1
			if kab == k:
				print(total_time)
				break
			iab += 1
		else:
			total_time += A[ia] + B[ib]
			kab += 1
			if kab == k:
				print(total_time)
				break
			ia += 1
			ib += 1
	else:
		total_time += A[ia] + B[ib]
		kab += 1
		if kab == k:
			print(total_time)
			break
		ia += 1
		ib += 1


import bisect
import os
import gc
import sys
from io import BytesIO, IOBase
from collections import Counter
from collections import deque
import heapq
import math
import statistics

def sin():
	return input()

def ain():
	return list(map(int, sin().split()))

def sain():
	return input().split()

def iin():
	return int(sin())
MAX = float('inf')
MIN = float('-inf')
MOD = 1000000007

def readTree(n, m):
	adj = [deque([]) for _ in range(n + 1)]
	for _ in range(m):
		(u, v) = ain()
		adj[u].append(v)
		adj[v].append(u)
	return adj

def main():
	(n, k) = ain()
	d = deque([])
	a = 0
	b = 0
	for _ in range(n):
		x = ain()
		if x[1] == 1:
			a += 1
		if x[2] == 1:
			b += 1
		d.append(x)
	if a < k or b < k:
		print(-1)
	else:
		both = deque([])
		a = deque([])
		b = deque([])
		for i in range(n):
			if d[i][1] == 1 and d[i][2] == 1:
				both.append(d[i][0])
			elif d[i][1] == 1 and d[i][2] == 0:
				a.append(d[i][0])
			elif d[i][1] == 0 and d[i][2] == 1:
				b.append(d[i][0])
		a = sorted(a)
		b = sorted(b)
		for i in range(min(len(a), len(b))):
			both.append(a[i] + b[i])
		both = sorted(both)
		print(sum(both[0:k]))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


(n, k) = map(int, input().split())
L1 = []
L2 = []
L3 = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		L1.append(t)
	elif a == 1 and b == 0:
		L2.append(t)
	elif a == 0 and b == 1:
		L3.append(t)
L3.sort()
L2.sort()
for i in range(min(len(L2), len(L3))):
	L1.append(L2[i] + L3[i])
if k <= len(L1):
	L1.sort()
	print(sum(L1[:k]))
else:
	print(-1)


import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
(n, k) = value()
alice = []
bob = []
both = []
for i in range(n):
	(t, a, b) = value()
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
alice.sort()
bob.sort()
both.sort()
ans = 0
if len(bob) + len(both) < k or len(alice) + len(both) < k:
	print(-1)
	exit()
if len(alice) < k:
	dif = k - len(alice)
	ans += sum(both[:dif])
	both = both[dif:]
	k -= dif
if len(bob) < k:
	dif = k - len(bob)
	ans += sum(both[:dif])
	both = both[dif:]
	k -= dif
a = 0
b = 0
bo = 0
for i in range(k):
	if bo < len(both) and alice[a] + bob[b] > both[bo]:
		ans += both[bo]
		bo += 1
	else:
		ans += alice[a] + bob[b]
		a += 1
		b += 1
print(ans)


(n, k1) = map(int, input().split())
c = []
a = []
b = []
for i in range(n):
	(x, y, z) = map(int, input().split())
	if y == z == 1:
		c.append(x)
	elif y == 1 and z == 0:
		a.append(x)
	elif y == 0 and z == 1:
		b.append(x)
a.sort()
b.sort()
c.sort()
ka = k1
kb = k1
(i, j, k) = (0, 0, 0)
ans = 0
while ka > 0 and kb > 0 and (i < len(a)) and (j < len(b)) and (k < len(c)):
	if a[i] + b[j] <= c[k]:
		ans += a[i] + b[j]
		ka -= 1
		kb -= 1
		i += 1
		j += 1
	else:
		ans += c[k]
		ka -= 1
		kb -= 1
		k += 1
if i >= len(a) and ka > 0:
	while k < len(c) and ka > 0:
		ans += c[k]
		k += 1
		ka -= 1
		kb = max(0, kb - 1)
elif j >= len(b) and kb > 0:
	while k < len(c) and kb > 0:
		ans += c[k]
		k += 1
		ka = max(0, ka - 1)
		kb -= 1
while i < len(a) and ka > 0:
	ans += a[i]
	ka -= 1
	i += 1
while j < len(b) and kb > 0:
	ans += b[j]
	kb -= 1
	j += 1
if ka == kb == 0:
	print(ans)
else:
	print(-1)


(n, k) = map(int, input().split())
only_alice = []
only_bob = []
both = []
alice_like = 0
bob_like = 0
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		alice_like += 1
		bob_like += 1
		both.append(t)
	elif a == 1 and b == 0:
		alice_like += 1
		only_alice.append(t)
	elif a == 0 and b == 1:
		bob_like += 1
		only_bob.append(t)
if alice_like < k or bob_like < k:
	print(-1)
else:
	both.sort()
	only_alice.sort()
	only_bob.sort()
	(x, y, z) = (0, 0, 0)
	choose = 0
	res = 0
	while choose < k:
		if z >= len(both):
			res += only_alice[x] + only_bob[y]
			x += 1
			y += 1
		elif x >= len(only_alice) or y >= len(only_bob):
			res += both[z]
			z += 1
		elif only_alice[x] + only_bob[y] < both[z]:
			res += only_alice[x] + only_bob[y]
			x += 1
			y += 1
		else:
			res += both[z]
			z += 1
		choose += 1
	print(res)


from collections import deque
import sys
import heapq

def inp():
	return sys.stdin.readline().strip()
for _ in range(1):
	(n, k) = map(int, inp().split())
	l = []
	a = []
	b = []
	for i in range(n):
		(ti, ai, bi) = map(int, inp().split())
		if ai == 0 and bi == 0:
			continue
		elif ai == 0:
			b.append(ti)
		elif bi == 0:
			a.append(ti)
		else:
			l.append(ti)
	if len(a) + len(l) < k or len(b) + len(l) < k:
		print(-1)
		continue
	a.sort()
	b.sort()
	l.sort()
	heapq.heapify(l)
	q = l
	for i in range(min(len(a), len(b))):
		heapq.heappush(q, a[i] + b[i])
	if len(q) < k:
		print(-1)
	ans = 0
	while k > 0:
		ans += heapq.heappop(q)
		k -= 1
	print(ans)


import math
import collections
import sys

def inpu():
	return input().split(' ')

def inti(a):
	for i in range(len(a)):
		a[i] = int(a[i])
	return a

def inp():
	a = inpu()
	a = inti(a)
	return a
a = inp()
(n, k) = (a[0], a[1])
bob = []
alice = []
common = []
for i in range(n):
	a = inp()
	if a[1] == 1 and a[2] == 1:
		common.append(a[0])
	elif a[1] == 1 and a[2] == 0:
		bob.append(a[0])
	elif a[1] == 0 and a[2] == 1:
		alice.append(a[0])
bob.sort()
alice.sort()
common.sort()
l1 = len(bob)
l2 = len(alice)
l3 = len(common)
if l1 + l3 < k or l2 + l3 < k:
	print(-1)
	exit(0)
bobptr = 0
aliceptr = 0
commonptr = 0
cost = 0
while k > 0:
	if commonptr >= l3 or (bobptr < l1 and aliceptr < l2 and (commonptr < l3) and (bob[bobptr] + alice[aliceptr] < common[commonptr])):
		cost = cost + bob[bobptr] + alice[aliceptr]
		k -= 1
		bobptr += 1
		aliceptr += 1
	else:
		cost = cost + common[commonptr]
		commonptr += 1
		k -= 1
print(cost)


from sys import stdin, stdout
import math, queue, heapq
fastinput = stdin.readline
fastout = stdout.write
z = 1
while z:
	z -= 1
	(n, k) = map(int, fastinput().split())
	common = []
	onlyx = []
	onlyy = []
	for i in range(n):
		(t, x, y) = map(int, fastinput().split())
		if x == 0 and y == 0:
			continue
		elif x == 1 and y == 1:
			common.append(t)
		elif x == 0 and y == 1:
			onlyy.append(t)
		else:
			onlyx.append(t)
	onlyy.sort()
	onlyx.sort()
	if len(onlyx) > k:
		onlyx = onlyx[:k]
	if len(onlyy) > k:
		onlyy = onlyy[:k]
	if len(onlyy) + len(common) < k or len(onlyx) + len(common) < k:
		print(-1)
	else:
		for i in range(min(len(onlyx), len(onlyy))):
			common.append(onlyx[i] + onlyy[i])
		common.sort()
		print(sum(common[:k]))


from sys import stdin, stdout
import sys
from math import *
(n, k) = map(int, input().split())
a = []
bt = []
b = []
for i in range(n):
	(x, y, z) = map(int, input().split())
	if y == z == 1:
		bt.append(x)
	elif y == 1:
		a.append(x)
	elif z == 1:
		b.append(x)
a.sort()
bt.sort()
b.sort()
ans = inf
for i in range(1, len(a)):
	a[i] = a[i] + a[i - 1]
for i in range(1, len(b)):
	b[i] = b[i] + b[i - 1]
for i in range(1, len(bt)):
	bt[i] += bt[i - 1]
y = min(len(bt), k)
while y >= 0:
	x = min(len(a), len(b), k - y - 1)
	if x == -1:
		ans = min(ans, bt[y - 1])
	elif y == 0 and x < len(a) and (x < len(b)):
		ans = min(ans, a[x] + b[x])
	elif y + x + 1 == k and x < len(a) and (x < len(b)):
		ans = min(ans, bt[y - 1] + a[x] + b[x])
	y -= 1
if ans == inf:
	print(-1)
else:
	print(ans)


def func(n, k):
	common = []
	bob = []
	alice = []
	for i in range(n):
		(t, a, b) = map(int, input().split())
		if a and b:
			common.append(t)
		elif a:
			alice.append(t)
		elif b:
			bob.append(t)
	if len(common) + len(alice) < k or len(common) + len(bob) < k:
		print(-1)
		return
	common.sort()
	alice.sort()
	bob.sort()
	c_num = min(k, len(common))
	num = k - c_num
	while c_num != 0 and num < len(alice) and (num < len(bob)) and (common[c_num - 1] > alice[num] + bob[num]):
		c_num -= 1
		num += 1
	print(sum(common[:c_num]) + sum(alice[:num]) + sum(bob[:num]))
for i in range(1):
	(n, k) = map(int, input().split())
	func(n, k)


initial = input().strip().split(' ')
books = int(initial[0])
likes = int(initial[1])
alice_list = []
bob_list = []
both_list = []
for i in range(books):
	line_input = input().strip().split(' ')
	time = int(line_input[0])
	alice = int(line_input[1]) == 1
	bob = int(line_input[2]) == 1
	if alice and bob:
		both_list.append(time)
	elif alice:
		alice_list.append(time)
	elif bob:
		bob_list.append(time)
alice_list.sort()
bob_list.sort()
length = min(len(alice_list), len(bob_list))
separate_list = []
for i in range(length):
	separate_list.append(alice_list[i] + bob_list[i])
total_list = both_list + separate_list
if len(total_list) < likes:
	print(-1)
else:
	total_list.sort()
	total = 0
	for r in range(likes):
		total += total_list[r]
	print(total)


def reading(numb, mass, c1, c2):
	if c1 < numb or c2 < numb:
		return -1
	true_mass1 = []
	true_mass2 = []
	true_mass3 = []
	for i in mass:
		if i[1] != 0 or i[2] != 0:
			if i[1] == 0:
				true_mass1.append(i)
			elif i[2] == 0:
				true_mass2.append(i)
			else:
				true_mass3.append(i)
	true_mass1.sort(key=lambda p: p[0])
	true_mass2.sort(key=lambda p: p[0])
	true_mass3.sort(key=lambda p: p[0])
	i = 0
	j = 0
	k = 0
	deltai = len(true_mass3)
	deltaj = len(true_mass2)
	deltak = len(true_mass1)
	result = 0
	for d in range(numb):
		if deltai != i and deltaj != j and (deltak != k):
			if true_mass3[i][0] <= true_mass2[j][0] + true_mass1[k][0]:
				result += true_mass3[i][0]
				i += 1
			else:
				result += true_mass2[j][0] + true_mass1[k][0]
				k += 1
				j += 1
		elif deltai == i:
			result += true_mass2[j][0] + true_mass1[k][0]
			k += 1
			j += 1
		elif deltaj == j or deltak == k:
			result += true_mass3[i][0]
			i += 1
	return result
t = [int(i) for i in input().strip().split()]
n = t[1]
count1 = 0
count2 = 0
mass = []
for i in range(t[0]):
	string = [int(j) for j in input().strip().split()]
	mass.append(string)
	if string[1] == 1:
		count1 += 1
	if string[2] == 1:
		count2 += 1
print(reading(n, mass, count1, count2))


(n, k) = [int(x) for x in input().split(' ')]
time = []
a = []
b = []
for i in range(n):
	(p, q, r) = [int(x) for x in input().split(' ')]
	time.append(p)
	a.append(q)
	b.append(r)
oa = []
ob = []
bo = []
no = []
for i in range(n):
	if a[i] and b[i]:
		bo.append(i)
	elif a[i] and b[i] == 0:
		oa.append(i)
	elif a[i] == 0 and b[i]:
		ob.append(i)
	else:
		no.append(i)
if len(bo) + len(oa) < k or len(bo) + len(ob) < k:
	print(-1)
else:

	def time_req(i):
		return time[i]
	oa.sort(key=time_req)
	ob.sort(key=time_req)
	bo.sort(key=time_req)
	oa.reverse()
	ob.reverse()
	bo.reverse()
	books = set()
	for i in range(k):
		if len(oa) == 0 or len(ob) == 0:
			books.add(bo.pop())
			continue
		elif len(bo) == 0:
			books.add(oa.pop())
			books.add(ob.pop())
			continue
		if time[bo[-1]] < time[oa[-1]] + time[ob[-1]] or len(oa) == 0 or len(ob) == 0:
			books.add(bo.pop())
		else:
			books.add(oa.pop())
			books.add(ob.pop())
	print(sum(list(map(time_req, list(books)))))


(n, k) = map(int, input().split())
a = []
b = []
ab = []
counta = 0
countb = 0
for x in range(n):
	(t, p, q) = map(int, input().split())
	if p == 1 and q == 1:
		counta = counta + 1
		countb = countb + 1
		ab.append(t)
	elif p == 1 and q != 1:
		counta = counta + 1
		a.append(t)
	elif q == 1 and p != 1:
		countb = countb + 1
		b.append(t)
if counta >= k and countb >= k:
	a.sort()
	b.sort()
	for x in range(min(len(a), len(b))):
		ab.append(a[x] + b[x])
	res = 0
	ab.sort()
	for x in range(k):
		res = res + ab[x]
	print(res)
else:
	print(-1)


import os, sys
from io import IOBase, BytesIO
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def get_input(a=str):
	return a(input())

def get_int_input():
	return get_input(int)

def get_input_arr(a):
	return list(map(a, input().split()))

def get_int_input_arr():
	return get_input_arr(int)

def solve():
	(n, k) = get_int_input_arr()
	books_both = []
	books_a = []
	books_b = []
	for _ in range(n):
		(t_i, a_i, b_i) = get_int_input_arr()
		if a_i == 1 and b_i == 1:
			books_both.append(t_i)
		elif a_i == 1 and b_i == 0:
			books_a.append(t_i)
		elif a_i == 0 and b_i == 1:
			books_b.append(t_i)
	books_both.sort()
	books_a.sort()
	books_b.sort()
	prefx_both = [0] * (len(books_both) + 1)
	for i in range(1, len(books_both) + 1):
		prefx_both[i] = prefx_both[i - 1] + books_both[i - 1]
	prefx_a = [0] * (len(books_a) + 1)
	for i in range(1, len(books_a) + 1):
		prefx_a[i] = prefx_a[i - 1] + books_a[i - 1]
	prefx_b = [0] * (len(books_b) + 1)
	for i in range(1, len(books_b) + 1):
		prefx_b[i] = prefx_b[i - 1] + books_b[i - 1]

	def can_do(time):
		for i in range(min(k + 1, len(books_both) + 1)):
			both_books_time = prefx_both[i]
			left_nums = k - i
			if left_nums < 0 or left_nums >= len(prefx_a) or left_nums >= len(prefx_b):
				continue
			books_a_time = prefx_a[left_nums]
			books_b_time = prefx_b[left_nums]
			if time >= both_books_time + books_a_time + books_b_time:
				return True
		return False
	lo = 0
	hi = 10 ** 10
	res = float('inf')
	while lo <= hi:
		mid = lo + (hi - lo) // 2
		if can_do(mid):
			res = mid
			hi = mid - 1
		else:
			lo = mid + 1
	if res == float('inf'):
		cout << -1 << endl
	else:
		cout << res << endl

def main():
	solve()
main()


from heapq import *
(n, k) = [int(x) for x in input().split()]
alice = []
bob = []
both = []
for _ in range(n):
	(t, a, b) = [int(x) for x in input().split()]
	if a and b:
		heappush(both, t)
	elif a:
		heappush(alice, t)
	elif b:
		heappush(bob, t)
while len(alice) and len(bob):
	heappush(both, heappop(alice) + heappop(bob))
if len(both) < k:
	print(-1)
else:
	time = 0
	for _ in range(k):
		time += heappop(both)
	print(time)


import sys
input = sys.stdin.readline
from collections import defaultdict
(n, k) = map(int, input().split())
(c1, c2) = (k, k)
(both, al, bob) = ([], [], [])
(co1, co2) = (0, 0)
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		both.append(t)
		co1 += 1
		co2 += 1
	elif a == 1:
		al.append(t)
		co1 += 1
	elif b == 1:
		bob.append(t)
		co2 += 2
if co1 < k or co2 < k:
	print(-1)
	exit()
maxa = max(len(both), len(al), len(bob))
for i in range(len(both), 3 * k):
	both.append(1000000000000)
for i in range(len(al), 3 * k):
	al.append(1000000000000)
for i in range(len(bob), 3 * k):
	bob.append(1000000000000)
both.sort()
al.sort()
bob.sort()
ans = 0
(i, j, k) = (0, 0, 0)
while c1 > 0 and c2 > 0:
	if both[i] <= al[j] + bob[k]:
		ans += both[i]
		c1 -= 1
		c2 -= 1
		i += 1
	else:
		ans += al[j]
		ans += bob[k]
		j += 1
		k += 1
		c1 -= 1
		c2 -= 1
if ans >= 1000000000000:
	print(-1)
else:
	print(ans)


import sys
import math
import heapq
from collections import defaultdict, deque
input = sys.stdin.readline

def r():
	return int(input())

def rm():
	return map(int, input().split())

def rl():
	return list(map(int, input().split()))
(n, k) = rm()
a = []
b = []
both = []
for _ in range(n):
	(t, ai, bi) = rm()
	if ai == 1 and bi == 1:
		both.append(t)
	elif ai == 1:
		a.append(t)
	elif bi == 1:
		b.append(t)
a.sort()
b.sort()
if len(a) < k - len(both) or len(b) < k - len(both):
	print(-1)
else:
	c = []
	cl = min(len(a), len(b))
	for i in range(cl):
		c.append(a[i] + b[i])
	both += c
	both.sort()
	print(sum(both[:k]))


from sys import stdin
(n, k) = map(int, stdin.readline().split())
(ba, bb, bc) = ([], [], [])
for _ in range(n):
	(t, a, b) = map(int, stdin.readline().split())
	if a and b:
		bc.append(t)
	elif a:
		ba.append(t)
	elif b:
		bb.append(t)
ba.sort()
bb.sort()
bc.sort()
(a, b, c) = (0, 0, 0)
T = 0
while k:
	if c < len(bc) and a < len(ba) and (b < len(bb)):
		if bc[c] < ba[a] + bb[b]:
			T += bc[c]
			c += 1
			k -= 1
		else:
			T += ba[a] + bb[b]
			a += 1
			b += 1
			k -= 1
	elif c < len(bc):
		T += bc[c]
		c += 1
		k -= 1
	elif a < len(ba) and b < len(bb):
		T += ba[a] + bb[b]
		a += 1
		b += 1
		k -= 1
	else:
		T = -1
		break
print(T)


from sys import stdout, stdin
input = stdin.buffer.readline
(n, k) = map(int, input().split())
alice = [0]
bob = [0]
common = [0]
la = 1
lb = 1
lc = 1
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		common.append(t)
		lc += 1
	elif a == 1:
		alice.append(t)
		la += 1
	elif b == 1:
		bob.append(t)
		lb += 1
alice.sort()
bob.sort()
common.sort()
alicecum = []
bobcum = []
commoncum = []
tot = 0
for num in alice:
	tot += num
	alicecum.append(tot)
tot = 0
for num in bob:
	tot += num
	bobcum.append(tot)
tot = 0
for num in common:
	tot += num
	commoncum.append(tot)
if la + lc - 2 < k or lb + lc - 2 < k:
	stdout.write(str(-1) + '\n')
else:
	res = 100000000000055
	for i in range(k + 1):
		com = k - i
		(al, bo) = (i, i)
		if com < lc and al < la and (bo < lb):
			temp = commoncum[com]
			temp += alicecum[al]
			temp += bobcum[bo]
			res = min(res, temp)
	stdout.write(str(res) + '\n')


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
(n, k) = map(int, input().split())
total = 0
alice = []
bob = []
both = []
for j in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
both.sort()
bob.sort()
alice.sort()
both.reverse()
bob.reverse()
alice.reverse()
if len(both) + len(alice) < k or len(bob) + len(both) < k:
	print(-1)
else:
	countera = 0
	counterb = 0
	summy = 0
	while countera < k or counterb < k:
		if countera < k and counterb < k:
			if len(both) > 0:
				if len(alice) > 0 and len(bob) > 0:
					val1 = both[-1]
					val2 = alice[-1] + bob[-1]
					if val1 <= val2:
						summy += val1
						both.pop()
					else:
						summy += val2
						alice.pop()
						bob.pop()
				else:
					summy += both.pop()
			else:
				summy += alice.pop() + bob.pop()
			countera += 1
			counterb += 1
		elif countera < k:
			if len(both) > 0:
				val1 = both[-1]
				val2 = alice[-1]
				if val1 <= val2:
					summy += val1
					both.pop()
				else:
					summy += val2
					alice.pop()
			else:
				summy += alice.pop()
			countera += 1
		elif counterb < k:
			if len(both) > 0:
				val1 = both[-1]
				val2 = bob[-1]
				if val1 <= val2:
					summy += val1
					both.pop()
				else:
					summy += val2
					bob.pop()
			else:
				summy += bob.pop()
			counterb += 1
	print(summy)


(N, K) = [int(i) for i in input().split()]
(T, A, B) = ([], [], [])
Tall = []
Talice = []
Tbob = []
for i in range(N):
	(t, a, b) = [int(j) for j in input().split()]
	T.append(t)
	A.append(a)
	B.append(b)
	if a and b:
		Tall.append(t)
	elif a:
		Talice.append(t)
	elif b:
		Tbob.append(t)
Tall = sorted(Tall)
Talice = sorted(Talice)
Tbob = sorted(Tbob)
iall = 0
isep = 0
ans = 0
ml = min(len(Talice), len(Tbob))
for i in range(K):
	if iall >= len(Tall) and isep >= ml:
		ans = -1
		break
	if iall < len(Tall) and (isep >= ml or Tall[iall] <= Talice[isep] + Tbob[isep]):
		ans += Tall[iall]
		iall += 1
	else:
		ans += Talice[isep] + Tbob[isep]
		isep += 1
print(ans)


(n, k) = map(int, input().split())
li = [[list(), list()], [list(), list()]]
for i in range(n):
	(a, b, c) = map(int, input().split())
	li[b][c].append(a)
cnt = 0
(itr1, itr2, itr3) = (0, 0, 0)
li[0][1].sort()
li[1][0].sort()
li[1][1].sort()
ttl = 0
run = True
for i in range(k):
	sm = 0
	if itr1 != len(li[0][1]) and itr2 != len(li[1][0]):
		sm = li[0][1][itr1] + li[1][0][itr2]
		if itr3 != len(li[1][1]):
			if sm < li[1][1][itr3]:
				itr1 += 1
				itr2 += 1
				ttl += sm
			else:
				ttl += li[1][1][itr3]
				itr3 += 1
		else:
			itr1 += 1
			itr2 += 1
			ttl += sm
	elif itr3 != len(li[1][1]):
		ttl += li[1][1][itr3]
		itr3 += 1
	else:
		run = False
		break
if run:
	print(ttl)
else:
	print(-1)


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
both = []
ali = []
bli = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		both.append(t)
	if a == 1 and b == 0:
		ali.append(t)
	if a == 0 and b == 1:
		bli.append(t)
lboth = len(both)
lali = len(ali)
lbli = len(bli)
if lboth + lali < k or lboth + lbli < k:
	print(-1)
else:
	both.sort(reverse=True)
	ali.sort(reverse=True)
	bli.sort(reverse=True)
	ans = 0
	for i in range(k):
		if lboth != 0 and lali != 0 and (lbli != 0):
			if both[-1] <= ali[-1] + bli[-1]:
				ans += both[-1]
				both.pop()
				lboth -= 1
			else:
				ans += ali[-1] + bli[-1]
				lali -= 1
				lbli -= 1
				ali.pop()
				bli.pop()
		elif lboth == 0:
			ans += ali[-1] + bli[-1]
			lali -= 1
			lbli -= 1
			ali.pop()
			bli.pop()
		elif lali == 0 or lbli == 0:
			ans += both[-1]
			both.pop()
			lboth -= 1
	print(ans)


import sys
input = sys.stdin.readline
INF = 10 ** 18
(n, m, k) = map(int, input().split())
B = [tuple(map(int, input().split())) for _ in range(n)]
GB = []
AB = []
BB = []
RB = []
for (i, (t, a, b)) in enumerate(B):
	if a and b:
		GB.append((t, i))
	elif a:
		AB.append((t, i))
	elif b:
		BB.append((t, i))
	else:
		RB.append((t, i))
GB.sort()
AB.sort()
BB.sort()
CB = sorted(((t1 + t2, i1, i2) for ((t1, i1), (t2, i2)) in zip(AB, BB)))
N = 1
while N <= 10 ** 4:
	N *= 2
T = [(0, 0)] * (2 * N)

def comb(a, b):
	return (a[0] + b[0], a[1] + b[1])

def add_book(t, inc=1):
	i = t + N
	T[i] = comb(T[i], (t * inc, inc))
	while i > 1:
		i //= 2
		T[i] = comb(T[i * 2], T[i * 2 + 1])

def query(x):
	assert x >= 0
	s = 0
	i = 1
	while x:
		(ts, tc) = T[i]
		if tc < x:
			return INF
		elif tc == x:
			s += ts
			break
		if i >= N:
			s += ts // tc * x
			break
		i *= 2
		if T[i][1] < x:
			s += T[i][0]
			x -= T[i][1]
			i += 1
	return s
for (t, _) in RB:
	add_book(t)
for (t, _) in AB:
	add_book(t)
for (t, _) in BB:
	add_book(t)
gb_i = 0
gb_t = 0
while gb_i < min(len(GB), m):
	gb_t += GB[gb_i][0]
	gb_i += 1
for (t, _) in GB[gb_i:]:
	add_book(t)
cb_i = 0
cb_t = 0
while gb_i + cb_i < k and gb_i + 2 * (cb_i + 1) <= m and (cb_i < len(CB)):
	cb_t += CB[cb_i][0]
	add_book(AB[cb_i][0], -1)
	add_book(BB[cb_i][0], -1)
	cb_i += 1
if gb_i + cb_i < k:
	print(-1)
	sys.exit()
best = (INF, -1, -1)
while True:
	best = min(best, (gb_t + cb_t + query(m - 2 * cb_i - gb_i), gb_i, cb_i))
	if not gb_i:
		break
	gb_i -= 1
	gb_t -= GB[gb_i][0]
	add_book(GB[gb_i][0])
	if gb_i + cb_i < k:
		if cb_i == len(CB):
			break
		cb_t += CB[cb_i][0]
		add_book(AB[cb_i][0], -1)
		add_book(BB[cb_i][0], -1)
		cb_i += 1
		if gb_i + 2 * cb_i > m:
			break
(bs, bi, bj) = best
assert bs != INF
ans = []
comps = 0
for (t, i) in GB[:bi]:
	ans.append(i + 1)
	comps += t
for (t, i1, i2) in CB[:bj]:
	ans.append(i1 + 1)
	ans.append(i2 + 1)
	comps += t
if bi + 2 * bj < m:
	rem = GB[bi:] + AB[bj:] + BB[bj:] + RB
	rem.sort()
	for (t, i) in rem[:m - bi - 2 * bj]:
		ans.append(i + 1)
		comps += t
assert comps == bs
print(bs)
print(*ans)


(n, k) = map(int, input().split())
list1 = []
list2 = []
list3 = []
for i in range(n):
	(x, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		list1.append(x)
	elif a == 1:
		list2.append(x)
	elif b == 1:
		list3.append(x)
list2.sort()
list3.sort()
for i in range(min(len(list2), len(list3))):
	list1.append(list2[i] + list3[i])
list1.sort()
l = len(list1)
if l < k:
	print(-1)
else:
	print(sum(list1[0:k]))


(n, k) = map(int, input().split())
a = []
b = []
ab = []
ans = 0
for _ in range(n):
	(t1, a1, b1) = map(int, input().split())
	if a1 == 1 and b1 == 1:
		ab.append(t1)
	elif a1 == 1 and b1 == 0:
		a.append(t1)
	elif a1 == 0 and b1 == 1:
		b.append(t1)
	else:
		pass
a.sort()
b.sort()
ab.sort()
if len(ab) + len(a) < k or len(ab) + len(b) < k:
	print('-1')
else:
	(lena, lenb, lenab) = (len(a), len(b), len(ab))
	(i, j) = (0, 0)
	for _ in range(k):
		if i < lena and i < lenb and (j < lenab):
			if a[i] + b[i] < ab[j]:
				ans += a[i] + b[i]
				i += 1
			else:
				ans += ab[j]
				j += 1
		elif i < lena and i < lenb:
			ans += a[i] + b[i]
			i += 1
		else:
			ans += ab[j]
			j += 1
	print(ans)


import sys

def swap(x, y, a):
	temp = a[x]
	a[x] = a[y]
	a[y] = temp
	return a

def solve():
	return None

def main():
	q = []
	for line in sys.stdin.readlines():
		q.append(line)
	for i in range(len(q)):
		q[i] = q[i].rstrip().split(' ')
		q[i] = [int(x) for x in q[i]]
	k = q[0][1]
	both = []
	only_left = []
	only_right = []
	for i in range(1, len(q)):
		if q[i][1] == 1 and q[i][2] == 1:
			both.append(q[i][0])
		elif q[i][1] == 1 and q[i][2] == 0:
			only_left.append(q[i][0])
		elif q[i][1] == 0 and q[i][2] == 1:
			only_right.append(q[i][0])
	only_left.sort()
	only_right.sort()
	for i in range(min(len(only_left), len(only_right))):
		both.append(only_left[i] + only_right[i])
	both.sort()
	if len(both) < k:
		print(-1)
	else:
		print(sum(both[:k]))
main()


def cta(t, p, r):
	global ana, iva, an
	ana[iva[t][p][1]] ^= True
	an += iva[t][p][0] * r
(n, k) = [int(x) for x in input().split()]
iva = [[] for _ in range(4)]
js = [() for _ in range(n)]
for i in range(n):
	(v, o, u) = [int(x) for x in input().split()]
	q = o << 1 | u
	iva[q].append((v, i))
	js[i] = (v, q)
for e in iva:
	e.sort()
(ct, a, r, ps, an) = (0, 0, 0, min(len(iva[1]), len(iva[2])), 0)
ana = [False] * n
for _ in range(k):
	if a < ps and r < len(iva[3]):
		if iva[1][a][0] + iva[2][a][0] < iva[3][r][0]:
			cta(1, a, 1)
			cta(2, a, 1)
			ct += 2
			a += 1
		else:
			cta(3, r, 1)
			ct += 1
			r += 1
	elif a < ps:
		cta(1, a, 1)
		cta(2, a, 1)
		ct += 2
		a += 1
	elif r < len(iva[3]):
		cta(3, r, 1)
		ct += 1
		r += 1
	else:
		print(-1)
		exit(0)
print(an)


(n, k) = map(int, input().split())
ab = []
a = []
b = []
for i in range(n):
	(t, c, d) = map(int, input().split())
	if c and d == 0:
		a.append(t)
	elif d and c == 0:
		b.append(t)
	elif c * d:
		ab.append(t)
a.sort()
b.sort()
ab.sort()
la = len(a)
lb = len(b)
lab = len(ab)
if la + lab < k or lb + lab < k:
	print(-1)
	exit()
if lb > la:
	(la, lb) = (lb, la)
	(a, b) = (b, a)
ans = 0
if lab >= k:
	ans += sum(ab[:k])
	now = k - 1
	na = 0
	nb = 0
	while nb < lb and now >= 0 and (ab[now] > a[na] + b[nb]):
		ans -= ab[now] - a[na] - b[nb]
		na += 1
		nb += 1
		now -= 1
else:
	ans += sum(ab) + sum(b[:k - lab]) + sum(a[:k - lab])
	now = lab - 1
	na = k - lab
	nb = k - lab
	while nb < lb and now >= 0 and (ab[now] > a[na] + b[nb]):
		ans -= ab[now] - a[na] - b[nb]
		na += 1
		nb += 1
		now -= 1
print(ans)


from sys import stdin
input = stdin.readline
INF = 10 ** 9 + 7
MAX = 10 ** 7 + 7
MOD = 10 ** 9 + 7
(n, k) = [int(x) for x in input().strip().split()]
(c, a, b) = ([], [], [])
for ni in range(n):
	(ti, ai, bi) = [int(x) for x in input().strip().split()]
	if ai == 1 and bi == 1:
		c.append(ti)
	elif ai == 1:
		a.append(ti)
	elif bi == 1:
		b.append(ti)
c.sort(reverse=True)
a.sort(reverse=True)
b.sort(reverse=True)
alen = len(a)
blen = len(b)
clen = len(c)
m = max(0, k - min(alen, blen))
ans = 0
if m > clen:
	print('-1')
else:
	for mi in range(m):
		ans += c.pop()
	ka = k - m
	kb = k - m
	while ka or kb:
		ca = c[-1] if c else float('inf')
		da = 0
		(ap, bp) = (0, 0)
		if ka:
			da += a[-1] if a else float('inf')
			ap = 1
		if kb:
			da += b[-1] if b else float('inf')
			bp = 1
		if da < ca:
			if ap:
				ka -= 1
				ans += a.pop() if a else float('inf')
			if bp:
				kb -= 1
				ans += b.pop() if b else float('inf')
		else:
			ans += c.pop() if c else float('inf')
			if ap:
				ka -= 1
			if bp:
				kb -= 1
	print(ans if ans != float('inf') else '-1')


import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict as dd

def main():
	(n, k) = map(int, input().split())
	(alike, blike) = (0, 0)
	(zero_one, one_zero, one_one, zero_zero) = ([], [], [], [])
	for i in range(n):
		(t, a, b) = map(int, input().split())
		alike += a
		blike += b
		if a == 0 and b == 1:
			zero_one.append((t, i))
		elif a == 1 and b == 0:
			one_zero.append((t, i))
		elif a == 1 and b == 1:
			one_one.append((t, i))
		else:
			pass
	if alike < k or blike < k:
		print(-1)
		exit()
	zero_one.sort(key=lambda x: x[0])
	one_one.sort(key=lambda x: x[0])
	one_zero.sort(key=lambda x: x[0])
	(alike, blike) = (0, 0)
	(zo, oo, oz, zz) = (0, 0, 0, 0)
	(lzo, loo, loz) = (len(zero_one), len(one_one), len(one_zero))
	tottime = 0
	while alike < k or blike < k:
		if alike < k and blike < k:
			if oo >= loo and zo >= lzo and (oz >= loz):
				print(-1)
				exit()
			elif zo >= lzo or oz >= loz:
				tottime += one_one[oo][0]
				oo += 1
			elif oo >= loo:
				tottime += zero_one[zo][0] + one_zero[oz][0]
				zo += 1
				oz += 1
			elif zero_one[zo][0] + one_zero[oz][0] < one_one[oo][0]:
				tottime += zero_one[zo][0] + one_zero[oz][0]
				zo += 1
				oz += 1
			else:
				tottime += one_one[oo][0]
				oo += 1
			alike += 1
			blike += 1
		elif alike == k and blike < k:
			if oo >= loo and zo >= lzo:
				print(-1)
				exit()
			elif oo >= loo:
				tottime += zero_one[zo][0]
				zo += 1
			elif zo >= lzo:
				tottime += one_one[oo][0]
				oo += 1
			elif zero_one[zo][0] < one_one[oo][0]:
				tottime += zero_one[zo][0]
				zo += 1
			else:
				tottime += one_one[oo][0]
				oo += 1
			blike += 1
		elif alike < k and blike == k:
			if oo >= loo and oz >= loz:
				print(-1)
				exit()
			elif oo >= loo:
				tottime += one_zero[oz][0]
				oz += 1
			elif oz >= loz:
				tottime += one_one[oo][0]
				oo += 1
			elif one_zero[oz][0] < one_one[oo][0]:
				tottime += one_zero[oz][0]
				oz += 1
			else:
				tottime += one_one[oo][0]
				oo += 1
	print(tottime)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def solution():
	aLike = []
	bLike = []
	bothLike = []
	(lines, k) = input().strip().split()
	lines = int(lines)
	k = int(k)
	for i in range(lines):
		(cost, isALike, isBLike) = input().strip().split()
		cost = int(cost)
		isALike = isALike == '1'
		isBLike = isBLike == '1'
		if isALike and isBLike:
			bothLike.append(cost)
		elif isALike:
			aLike.append(cost)
		elif isBLike:
			bLike.append(cost)
	aLike.sort()
	bLike.sort()
	bothLike.sort()
	aLike.reverse()
	bLike.reverse()
	bothLike.reverse()
	cost = 0
	while len(bothLike) > 0 and k > 0:
		if len(aLike) > 0 and len(bLike) > 0:
			if bothLike[-1] <= aLike[-1] + bLike[-1]:
				cost += bothLike.pop()
				k -= 1
			else:
				cost += aLike.pop()
				cost += bLike.pop()
				k -= 1
		else:
			cost += bothLike.pop()
			k -= 1
	while k > 0:
		if len(aLike) > 0 and len(bLike) > 0:
			cost += aLike.pop()
			cost += bLike.pop()
			k -= 1
		else:
			return -1
	return cost
print(solution())


(n, k) = [int(k) for k in input().split()]
tog = []
ali = []
bli = []
time = 0
size = 0
for i in range(n):
	(t, a, b) = [int(k) for k in input().split()]
	if a & b == 1:
		tog.append(t)
	else:
		if a == 1:
			ali.append(t)
		if b == 1:
			bli.append(t)
asi = len(tog) + len(ali)
bsi = len(tog) + len(bli)
if k > min(asi, bsi):
	print(-1)
else:
	ali.sort()
	bli.sort()
	for i in range(min(len(ali), len(bli))):
		tog.append(ali[i] + bli[i])
	tog.sort()
	for i in range(k):
		time += tog[i]
	print(time)


(n, k) = list(map(int, input().split()))
both = []
alice = []
bob = []
for i in range(n):
	(t, a, b) = list(map(int, input().split()))
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
both.sort()
alice.sort()
bob.sort()
x = 0
y = 0
if len(both) + len(alice) < k or len(both) + len(bob) < k:
	print(-1)
else:
	both.append(10 ** 9)
	alice.append(10 ** 9)
	bob.append(10 ** 9)
	i = 0
	j = 0
	time = 0
	alpha = 0
	while x < k and y < k:
		if i < len(both) and j < len(alice) and (alpha < len(bob)):
			if both[i] <= alice[j] + bob[alpha]:
				time += both[i]
				i += 1
				x += 1
				y += 1
			else:
				time += alice[j] + bob[alpha]
				j += 1
				alpha += 1
				x += 1
				y += 1
		elif len(both) != i:
			if len(alice) == 0:
				if len(bob) == 0:
					time += both[i]
					i += 1
					x += 1
					y += 1
	print(time)


import sys
input = lambda : sys.stdin.readline().rstrip()
inp = sys.stdin.buffer.readline

def I():
	return list(map(int, inp().split()))
inf = 10 ** 8
(n, k) = [int(i) for i in input().split()]
al = []
bo = []
bt = []
for i in range(n):
	x = [int(i) for i in input().split()]
	if x[1] == 1 and x[2] == 1:
		bt.append(x[0])
	elif x[1] == 0 and x[2] == 1:
		bo.append(x[0])
	elif x[1] == 1 and x[2] == 0:
		al.append(x[0])
al.sort()
bo.sort()
bt.sort()
if len(bt) + len(al) < k or len(bt) + len(bo) < k:
	print(-1)
	exit(0)
else:
	cnt = [[0, 0, 0] for i in range(max(len(al), len(bo), len(bt)))]
	for i in range(len(cnt)):
		if i < len(al):
			cnt[i][0] = al[i]
		else:
			cnt[i][0] = inf
		if i < len(bo):
			cnt[i][1] = bo[i]
		else:
			cnt[i][1] = inf
		if i < len(bt):
			cnt[i][2] = bt[i]
		else:
			cnt[i][2] = inf
	cnt.append([inf, inf, 2 * inf])
	k1 = k
	i = 0
	j = 0
	k = 0
	val = 0
	ans = 0
	while val != k1:
		if cnt[i][0] + cnt[j][1] >= cnt[k][2]:
			ans += cnt[k][2]
			val += 1
			k += 1
		else:
			ans += cnt[i][1] + cnt[j][0]
			val += 1
			i += 1
			j += 1
	print(ans)


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(n, k) = list(map(int, input().split()))
(z, x, y) = ([], [], [])
for i in range(n):
	(t, a, b) = list(map(int, input().split()))
	if a & b:
		z.append(t)
	elif a:
		x.append(t)
	elif b:
		y.append(t)
x = sorted(x)
y = sorted(y)
n = min(len(x), len(y))
for i in range(n):
	z.append(x[i] + y[i])
if len(z) >= k:
	z = sorted(z)[:k]
	print(sum(z))
else:
	print(-1)


import os
import sys
from io import BytesIO, IOBase

def main():
	(n, k) = map(int, input().split())
	(x, y, z) = ([], [], [])
	for _ in range(n):
		(t, a, b) = map(int, input().split())
		if a & b:
			z.append(t)
		elif a:
			x.append(t)
		elif b:
			y.append(t)
	x.sort()
	y.sort()
	for i in range(min(len(x), len(y))):
		z.append(x[i] + y[i])
	if len(z) < k:
		print(-1)
	else:
		print(sum(sorted(z)[:k]))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


INF = float('inf')

def tc():
	(n, k) = map(int, input().split())
	books = [tuple(map(int, input().split())) for _ in range(n)]
	(alice, bob, both) = ([], [], [])
	for (t, a, b) in books:
		if a and b:
			both.append(t)
		elif a:
			alice.append(t)
		elif b:
			bob.append(t)
	alice.sort()
	bob.sort()
	for (a, b) in zip(alice, bob):
		both.append(a + b)
	both.sort()
	if len(both) < k:
		print(-1)
	else:
		print(sum(both[:k]))
tc()


def solve():
	import sys
	nk = sys.stdin.readline().split()
	n = int(nk[0])
	k = int(nk[1])
	A = []
	B = []
	both = []
	for i in range(n):
		(t, a, b) = list(map(int, sys.stdin.readline().split()))
		if a == 1 and b == 0:
			A.append(t)
		if a == 0 and b == 1:
			B.append(t)
		if a == 1 and b == 1:
			both.append(t)
	A = sorted(A)
	B = sorted(B)
	both = sorted(both)
	pA = [0 for _ in range(len(A))]
	pB = [0 for _ in range(len(B))]
	p_both = [0 for _ in range(len(both))]
	if len(pA) > 0:
		pA[0] = A[0]
	if len(pB) > 0:
		pB[0] = B[0]
	if len(p_both) > 0:
		p_both[0] = both[0]
	for i in range(1, len(A)):
		pA[i] = pA[i - 1] + A[i]
	for i in range(1, len(B)):
		pB[i] = pB[i - 1] + B[i]
	for i in range(1, len(both)):
		p_both[i] = p_both[i - 1] + both[i]
	result = 10 ** 10
	for i in range(min(len(both) + 1, k + 1)):
		num = k - i
		if num > len(A) or num > len(B):
			continue
		s = 0
		if i > 0:
			s += p_both[i - 1]
		if num > 0:
			s += pA[num - 1] + pB[num - 1]
		result = min(result, s)
	if result == 10 ** 10:
		print(-1)
	else:
		print(result)
solve()


from sys import stdin
(n, k) = list(map(int, stdin.readline().strip().split(' ')))
AB = []
A = []
B = []
for i in range(n):
	(t, a, b) = list(map(int, stdin.readline().strip().split(' ')))
	if a == 1 and b == 1:
		AB.append(t)
	elif a == 1:
		A.append(t)
	elif b == 1:
		B.append(t)
AB.sort()
A.sort()
B.sort()
ans = 0
abi = 0
ai = 0
bi = 0
isPossible = True
for i in range(k):
	if abi == len(AB) and (ai == len(A) or bi == len(B)):
		isPossible = False
		break
	if abi == len(AB):
		ans += A[ai] + B[bi]
		ai += 1
		bi += 1
		continue
	if ai == len(A) or bi == len(B):
		ans += AB[abi]
		abi += 1
		continue
	if A[ai] + B[bi] <= AB[abi]:
		ans += A[ai] + B[bi]
		ai += 1
		bi += 1
		continue
	ans += AB[abi]
	abi += 1
	continue
if isPossible:
	print(ans)
else:
	print(-1)


from sys import stdin, stdout
input = stdin.readline
from collections import deque as dq
mp = lambda : map(int, input().split())
it = lambda : int(input())
(a, b) = mp()
comman = []
alice = []
bob = []
for books in range(a):
	(t, x, y) = mp()
	if x == y == 1:
		comman.append(t)
	elif x & 1:
		alice.append(t)
	elif y & 1:
		bob.append(t)
comman = dq(sorted(comman))
alice = dq(sorted(alice))
bob = dq(sorted(bob))
time = 0
while b:
	if len(alice) and len(bob) and len(comman):
		if alice[0] + bob[0] <= comman[0]:
			time += alice[0] + bob[0]
			alice.popleft()
			bob.popleft()
		else:
			time += comman[0]
			comman.popleft()
	else:
		if len(comman) == 0:
			if len(alice) >= b and len(bob) >= b:
				for ele in range(b):
					time += alice[ele] + bob[ele]
			else:
				time = -1
		elif len(comman) >= b:
			for ele in range(b):
				time += comman[ele]
		else:
			time = -1
		break
	b -= 1
print(time)


(n, k) = map(int, input().split())
both_like = []
alice_like = []
bob_like = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a and b:
		both_like.append((t, a, b))
	elif a:
		alice_like.append((t, a, b))
	elif b:
		bob_like.append((t, a, b))
alice_like.sort()
bob_like.sort()
for i in range(min(len(alice_like), len(bob_like))):
	both_like.append((alice_like[i][0] + bob_like[i][0], 1, 1))
both_like.sort()
if len(both_like) < k:
	print(-1)
else:
	ans = 0
	for i in range(k):
		ans += both_like[i][0]
	print(ans)


(t, k) = map(int, input().split())
A = []
B = []
C = []
for i in range(t):
	(a, b, c) = map(int, input().split())
	if b == 1 and c == 0:
		A.append(a)
	elif b == 0 and c == 1:
		B.append(a)
	elif b == 1:
		C.append(a)
if min(len(A), len(B)) + len(C) < k:
	print(-1)
else:
	A.sort()
	B.sort()
	s = 0
	for i in range(min(len(A), len(B))):
		C.append(A[i] + B[i])
	C.sort()
	for i in range(k):
		s += C[i]
	print(s)


def solve():
	(n, k) = list(map(int, input().split()))
	a = []
	b = []
	both = []
	alice = 0
	bob = 0
	coincidence = 0
	for i in range(n):
		(t, a_, b_) = list(map(int, input().split()))
		if b_ and a_:
			both.append(t)
			coincidence += 1
		elif a_ == 1:
			a.append(t)
			alice += 1
		elif b_ == 1:
			b.append(t)
			bob += 1
	if alice + coincidence < k or bob + coincidence < k:
		print(-1)
	else:
		a.sort()
		b.sort()
		for i in range(min(len(a), len(b))):
			both.append(a[i] + b[i])
		both.sort()
		out = sum(both[:k])
		print(out)
cases = 1
for test in range(cases):
	solve()


(n, k) = map(int, input().split())
d = []
l = []
a = []
b = []
for _ in range(n):
	(p, q, r) = map(int, input().split())
	if q == r:
		if q == 0:
			d.append(p)
		else:
			l.append(p)
	elif q == 0 and r == 1:
		b.append(p)
	else:
		a.append(p)
m = min(len(a), len(b))
if m + len(l) < k:
	print(-1)
else:
	a.sort()
	b.sort()
	s = [0] * m
	for i in range(m):
		s[i] = a[i] + b[i]
	r = s + l
	r.sort()
	print(sum(r[:k]))


from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
	return ord(i) - ord('a')

def solve():
	(n, k) = mi()
	x = []
	y = []
	z = []
	for i in range(n):
		a = li()
		if a[1] and a[2]:
			x.append(a[0])
		elif a[1] == 1:
			y.append(a[0])
		elif a[2] == 1:
			z.append(a[0])
	n1 = min(len(y), len(z))
	x.sort()
	y.sort()
	z.sort()
	for i in range(1, len(x)):
		x[i] += x[i - 1]
	for i in range(1, len(y)):
		y[i] += y[i - 1]
	for i in range(1, len(z)):
		z[i] += z[i - 1]
	if len(x) + n1 < k:
		print('-1')
		exit(0)
	ans = inf
	if len(x) >= k:
		ans = x[k - 1]
		n2 = 0
	else:
		n2 = k - len(x) - 1
	c = 0
	for i in range(n2, n1):
		if i >= k:
			break
		x2 = k - i - 1
		if x2 < 1:
			ans = min(ans, z[i] + y[i])
		else:
			ans = min(ans, x[x2 - 1] + z[i] + y[i])
		c += 1
	print(ans)
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	input = sys.stdin.readline
solve()


(n, k) = map(int, input().split())
both = []
alice = []
bob = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a and b:
		both.append(t)
	elif a:
		alice.append(t)
	elif b:
		bob.append(t)
alice.sort(reverse=True)
bob.sort(reverse=True)
both.sort(reverse=True)

def solve():
	ak = k
	bk = k
	v = 0
	while ak > 0 and bk > 0:
		if (not alice or not bob) and (not both):
			return -1
		if alice and bob and (not both or both[-1] > alice[-1] + bob[-1]):
			v += alice.pop() + bob.pop()
		else:
			v += both.pop()
		ak -= 1
		bk -= 1
	while ak > 0:
		if not alice and (not both):
			return -1
		if alice and (not both or both[-1] > alice[-1]):
			v += alice.pop()
		else:
			v += both.pop()
		ak -= 1
	while bk > 0:
		if not bob and (not both):
			return -1
		if bob and (not both or both[-1] > bob[-1]):
			v += bob.pop()
		else:
			v += both.pop()
		bk -= 1
	return v
print(solve())


from copy import copy, deepcopy

def read_int():
	return int(input())

def read_arr():
	return [int(x) for x in input().split(' ')]

def read_mx(n):
	return [[int(num) for num in input().split(' ')] for _ in range(0, n)]

def work(p_case):
	(n, k) = read_arr()
	mx = read_mx(n)
	b_only = []
	a_only = []
	both = []
	for row in mx:
		cost = row[0]
		if row[1] and (not row[2]):
			b_only.append(cost)
		elif row[2] and (not row[1]):
			a_only.append(cost)
		elif row[1] and row[2]:
			both.append(cost)
	b_only.sort()
	a_only.sort()
	(ia, ib) = (0, 0)
	while ia < len(a_only) and ib < len(b_only):
		both.append(a_only[ia] + b_only[ib])
		ia += 1
		ib += 1
	both.sort()
	(sm, cnt) = (0, 0)
	while cnt < k and cnt < len(both):
		sm += both[cnt]
		cnt += 1
	if cnt == k:
		print(sm)
	else:
		print(-1)
work(0)


import sys
(n, k) = map(int, input().split())
M = []
A = []
B = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		M.append(t)
	elif a == 1:
		A.append(t)
	elif b == 1:
		B.append(t)
if min(len(M) + len(A), len(M) + len(B)) < k:
	print(-1)
	sys.exit()
A.append(0)
B.append(0)
M.append(0)
A.sort()
B.sort()
M.sort()
for i in range(len(A) - 1):
	A[i + 1] += A[i]
for i in range(len(B) - 1):
	B[i + 1] += B[i]
for i in range(len(M) - 1):
	M[i + 1] += M[i]
ans = float('inf')
for i in range(k + 1):
	j = k - i
	if len(A) > i and len(B) > i and (len(M) > j):
		ans = min(ans, A[i] + B[i] + M[j])
print(ans)


for _ in range(1):
	(n, k) = map(int, input().split())
	al = []
	bo = []
	com = []
	for i in range(n):
		(t, a, b) = map(int, input().split())
		if a == b == 1:
			com.append(t)
		else:
			if a == 1:
				al.append(t)
			if b == 1:
				bo.append(t)
	com.sort(reverse=True)
	al.sort(reverse=True)
	bo.sort(reverse=True)
	ans = 0
	f = 0
	while k != 0:
		if len(al) > 0 and len(bo) > 0:
			c = al[-1] + bo[-1]
			if len(com) > 0 and c > com[-1]:
				ans += com[-1]
				com.pop()
			else:
				ans += c
				al.pop()
				bo.pop()
		elif len(com) > 0:
			ans += com[-1]
			com.pop()
		else:
			f = 1
			k = 1
		k -= 1
	if f == 0:
		print(ans)
	else:
		print(-1)


from collections import defaultdict
(n, k) = map(int, input().split())
d = defaultdict(lambda : [0, 0])
la = []
lb = []
lboth = []
(ca, cb, cboth) = (0, 0, 0)
for x in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		lboth.append(t)
		cboth += 1
	elif a == 1:
		la.append(t)
		ca += 1
		d[t][0] += 1
	elif b == 1:
		lb.append(t)
		d[t][1] += 1
		cb += 1
if ca + cboth < k or cb + cboth < k:
	print(-1)
else:
	la.sort()
	lb.sort()
	lboth.sort()
	(coa, cob) = (0, 0)
	ans = 0
	(a, b, c) = (0, 0, 0)
	while (coa < k or cob < k) == True:
		if c < cboth:
			if a < ca and b < cb:
				if lboth[c] <= la[a] + lb[b]:
					coa += 1
					cob += 1
					ans += lboth[c]
					c += 1
				else:
					coa += 1
					cob += 1
					ans += la[a] + lb[b]
					a += 1
					b += 1
			else:
				coa += 1
				cob += 1
				ans += lboth[c]
				c += 1
		else:
			break
	while coa < k:
		coa += 1
		ans += la[a]
		a += 1
	while cob < k:
		cob += 1
		ans += lb[b]
		b += 1
	print(ans)


def binary(a, start, end, e):
	mid = (start + end) // 2
	if a[mid] == e:
		return mid
	elif a[mid] > e:
		end = mid - 1
	else:
		start = mid + 1
	if start <= end:
		return binary(a, start, end, e)
	else:
		return start
(n, k) = map(int, input().split())
p = []
al = []
bo = []
for j in range(n):
	(a, b, c) = map(int, input().split())
	if b == 1 and c == 1:
		p.append(a)
	elif b == 1 and c == 0:
		al.append(a)
	elif b == 0 and c == 1:
		bo.append(a)
al.sort()
bo.sort()
if p != []:
	while al != [] and bo != []:
		v = al[0] + bo[0]
		p.append(v)
		del al[0]
		del bo[0]
else:
	while al != [] and bo != []:
		v = al[0] + bo[0]
		p.append(v)
		del al[0]
		del bo[0]
p.sort()
if len(p) < k:
	print(-1)
else:
	print(sum(p[:k]))


line = input().split()
(n, k) = (int(line[0]), int(line[1]))
(a, b, c) = ([], [], [])
for i in range(n):
	line = input().split()
	(t, ai, bi) = (int(line[0]), int(line[1]), int(line[2]))
	if ai == 1 and bi == 1:
		c.append(t)
	elif ai == 1:
		a.append(t)
	elif bi == 1:
		b.append(t)
a.sort()
b.sort()
c.sort()
(i, j, cnt) = (0, 0, 0)
ans = 0
while i < min(len(a), len(b)) and j < len(c) and (cnt < k):
	if a[i] + b[i] < c[j]:
		ans += a[i] + b[i]
		i += 1
	else:
		ans += c[j]
		j += 1
	cnt += 1
while i < min(len(a), len(b)) and cnt < k:
	ans += a[i] + b[i]
	cnt += 1
	i += 1
while j < len(c) and cnt < k:
	ans += c[j]
	cnt += 1
	j += 1
if cnt < k:
	print(-1)
else:
	print(ans)


import sys

def solve():
	(n, k) = map(int, sys.stdin.readline().split())
	list_book = [[], [], []]
	count = [0, 0, 0]
	for _ in range(n):
		(t, a, b) = map(int, sys.stdin.readline().split())
		if a and b:
			list_book[0].append(t)
			count[0] += 1
		elif a:
			list_book[1].append(t)
			count[1] += 1
		elif b:
			list_book[2].append(t)
			count[2] += 1
	if count[0] + min(count[1], count[2]) < k:
		print(-1)
		return
	list_book[0].sort(reverse=True)
	list_book[1].sort(reverse=True)
	list_book[2].sort(reverse=True)
	result = 0
	book = k
	result = 0
	for _ in range(k):
		next_time = 1000000000000000000000
		token = 0
		if list_book[1] and list_book[2]:
			next_time = list_book[1][-1] + list_book[2][-1]
		if list_book[0]:
			if next_time > list_book[0][-1]:
				next_time = list_book[0][-1]
				token = 1
		if token:
			list_book[0].pop()
		else:
			list_book[1].pop()
			list_book[2].pop()
		result += next_time
	print(result)
solve()


(nb_books, mins) = [int(x) for x in input().split()]
(x, y, z) = ([], [], [])
for i in range(nb_books):
	(n, a, b) = [int(x) for x in input().split()]
	if a & b:
		z.append(n)
	elif a:
		x.append(n)
	elif b:
		y.append(n)
x.sort()
y.sort()
for i in range(min(len(x), len(y))):
	z.append(x[i] + y[i])
answer = sum(sorted(z)[:mins])
print(-1 if len(z) < mins else answer)


(n, k) = map(int, input().split())
a = 0
b = 0
alike = []
blike = []
bothlike = []
for _ in range(n):
	(t, aa, bb) = map(int, input().split())
	if aa == 1:
		a += 1
	if bb == 1:
		b += 1
	if aa == 1 and bb == 0:
		alike.append(t)
	elif aa == 0 and bb == 1:
		blike.append(t)
	elif aa == 1 and bb == 1:
		bothlike.append(t)
if a < k or b < k:
	print(-1)
else:
	alike.sort()
	blike.sort()
	la = len(alike)
	lb = len(blike)
	ans = 0
	if la < k and lb >= k:
		for i in range(la):
			bothlike.append(alike[i] + blike[i])
		bothlike.sort()
		ans = sum(bothlike[:k])
	elif lb < k and la >= k:
		for i in range(lb):
			bothlike.append(alike[i] + blike[i])
		bothlike.sort()
		ans = sum(bothlike[:k])
	elif la >= k and lb >= k:
		for i in range(k):
			bothlike.append(alike[i] + blike[i])
		bothlike.sort()
		ans = sum(bothlike[:k])
	else:
		for i in range(min(la, lb)):
			bothlike.append(alike[i] + blike[i])
		bothlike.sort()
		ans = sum(bothlike[:k])
	print(ans)


from sys import stdin
(n, k) = list(map(int, stdin.readline().split()))
alice = []
bob = []
both = []
for _ in range(n):
	(t, a, b) = list(map(int, stdin.readline().split()))
	if a == b == 1:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
alice = sorted(alice)
bob = sorted(bob)
both = sorted(both)
(a, b, c) = (0, 0, 0)
res = 0
for _ in range(k):
	if c >= len(both) and (a >= len(alice) or b >= len(bob)):
		res = -1
		break
	if c >= len(both):
		res += alice[a]
		res += bob[b]
		a += 1
		b += 1
	elif a >= len(alice) or b >= len(bob):
		res += both[c]
		c += 1
	elif alice[a] + bob[b] < both[c]:
		res += alice[a]
		res += bob[b]
		a += 1
		b += 1
	elif both[c] <= alice[a] + bob[b]:
		res += both[c]
		c += 1
print(res)


def solution():
	s = input().split()
	n = int(s[0])
	k = int(s[1])
	yyLike = []
	xqLike = []
	bothLike = []
	s = 0
	for i in range(n):
		line = input().split()
		cost = int(line[0])
		if line[1] == '1' and line[2] == '1':
			bothLike.append(cost)
		elif line[1] == '1':
			yyLike.append(cost)
		elif line[2] == '1':
			xqLike.append(cost)
	yyLike.sort()
	xqLike.sort()
	bothLike.sort()
	yyLike.reverse()
	xqLike.reverse()
	bothLike.reverse()
	while k > 0 and len(bothLike) > 0:
		if len(yyLike) > 0 and len(xqLike) > 0:
			if bothLike[-1] < yyLike[-1] + xqLike[-1]:
				s += bothLike.pop()
				k -= 1
			else:
				s += yyLike.pop()
				s += xqLike.pop()
				k -= 1
		else:
			k -= 1
			s += bothLike.pop()
	while k > 0:
		if len(yyLike) == 0 or len(xqLike) == 0:
			return -1
		k -= 1
		s += yyLike.pop()
		s += xqLike.pop()
	return s
print(solution())


def solve():
	global B, K
	both = [b[0] for b in B if b[1] and b[2]]
	alice = sorted([b[0] for b in B if b[1] and (not b[2])])
	bob = sorted([b[0] for b in B if b[2] and (not b[1])])
	for i in range(min(len(alice), len(bob))):
		both.append(alice[i] + bob[i])
	if len(both) < K:
		return -1
	return sum(sorted(both)[:K])
(N, K) = map(int, input().split())
B = [tuple(map(int, input().split())) for _ in range(N)]
sol = solve()
print(sol)


from sys import stdin
from collections import defaultdict as dd
from collections import deque as dq
import itertools as it
from math import sqrt, log, log2
from fractions import Fraction
(n, k) = map(int, input().split())
(alike, blike) = (0, 0)
(zero_one, one_zero, one_one, zero_zero) = ([], [], [], [])
for i in range(n):
	(t, a, b) = map(int, input().split())
	alike += a
	blike += b
	if a == 0 and b == 1:
		zero_one.append((t, i))
	elif a == 1 and b == 0:
		one_zero.append((t, i))
	elif a == 1 and b == 1:
		one_one.append((t, i))
	else:
		pass
if alike < k or blike < k:
	print(-1)
	exit()
zero_one.sort(key=lambda x: x[0])
one_one.sort(key=lambda x: x[0])
one_zero.sort(key=lambda x: x[0])
(alike, blike) = (0, 0)
(zo, oo, oz, zz) = (0, 0, 0, 0)
(lzo, loo, loz) = (len(zero_one), len(one_one), len(one_zero))
tottime = 0
while alike < k or blike < k:
	if alike < k and blike < k:
		if oo >= loo and zo >= lzo and (oz >= loz):
			print(-1)
			exit()
		elif zo >= lzo or oz >= loz:
			tottime += one_one[oo][0]
			oo += 1
		elif oo >= loo:
			tottime += zero_one[zo][0] + one_zero[oz][0]
			zo += 1
			oz += 1
		elif zero_one[zo][0] + one_zero[oz][0] < one_one[oo][0]:
			tottime += zero_one[zo][0] + one_zero[oz][0]
			zo += 1
			oz += 1
		else:
			tottime += one_one[oo][0]
			oo += 1
		alike += 1
		blike += 1
	elif alike == k and blike < k:
		if oo >= loo and zo >= lzo:
			print(-1)
			exit()
		elif oo >= loo:
			tottime += zero_one[zo][0]
			zo += 1
		elif zo >= lzo:
			tottime += one_one[oo][0]
			oo += 1
		elif zero_one[zo][0] < one_one[oo][0]:
			tottime += zero_one[zo][0]
			zo += 1
		else:
			tottime += one_one[oo][0]
			oo += 1
		blike += 1
	elif alike < k and blike == k:
		if oo >= loo and oz >= loz:
			print(-1)
			exit()
		elif oo >= loo:
			tottime += one_zero[oz][0]
			oz += 1
		elif oz >= loz:
			tottime += one_one[oo][0]
			oo += 1
		elif one_zero[oz][0] < one_one[oo][0]:
			tottime += one_zero[oz][0]
			oz += 1
		else:
			tottime += one_one[oo][0]
			oo += 1
print(tottime)


from sys import stdin, stdout
import heapq

def input():
	return stdin.readline().strip()

def ans(both, alice_only, bob_only, neither, M, K):
	both_fc = [b[0] for b in both]
	neither_fc = [b[0] for b in neither]
	alice_only_fc = [a[0] for a in alice_only]
	bob_only_fc = [b[0] for b in bob_only]
	both_prefix = [0]
	for b in both_fc:
		both_prefix += [both_prefix[-1] + b]
	alice_only_prefix = [0]
	for b in alice_only_fc:
		alice_only_prefix += [alice_only_prefix[-1] + b]
	bob_only_prefix = [0]
	for b in bob_only_fc:
		bob_only_prefix += [bob_only_prefix[-1] + b]
	neither_prefix = [0]
	for b in neither_fc:
		neither_prefix += [neither_prefix[-1] + b]
	p = min(len(both), M)
	q = 0
	r = 0
	s = 0
	while p + q < K:
		if q == len(alice_only):
			break
		q += 1
	if p + q < K:
		return None
	while p + r < K:
		if r == len(bob_only):
			break
		r += 1
	if p + r < K:
		return None
	while p + q + r + s < M:
		g = dict()
		if q < len(alice_only):
			g['q'] = alice_only_fc[q]
		if r < len(bob_only):
			g['r'] = bob_only_fc[r]
		if s < len(neither):
			g['s'] = neither_fc[s]
		if len(g.keys()) == 0:
			return None
		to_increment = min(g, key=g.get)
		if to_increment == 'q':
			q += 1
		if to_increment == 'r':
			r += 1
		if to_increment == 's':
			s += 1
	while p + q + r + s > M:
		g = dict()
		if 0 < q and p + q > K:
			g['q'] = alice_only_fc[q - 1]
		if 0 < r and p + r > K:
			g['r'] = bob_only_fc[r - 1]
		if 0 < s:
			g['s'] = neither_fc[s - 1]
		if len(g.keys()) == 0:
			break
		to_decrement = max(g, key=g.get)
		if to_decrement == 'q':
			q -= 1
		if to_decrement == 'r':
			r -= 1
		if to_decrement == 's':
			s -= 1
	if p + q + r + s > M:
		return None
	best_score = both_prefix[p] + alice_only_prefix[q] + bob_only_prefix[r] + neither_prefix[s]
	best_pqrs = (p, q, r, s)
	while p > 0:
		p -= 1
		while p + q < K:
			if q == len(alice_only):
				break
			q += 1
		if p + q < K:
			break
		while p + r < K:
			if r == len(bob_only):
				break
			r += 1
		if p + r < K:
			break
		while p + q + r + s < M:
			g = dict()
			if q < len(alice_only):
				g['q'] = alice_only_fc[q]
			if r < len(bob_only):
				g['r'] = bob_only_fc[r]
			if s < len(neither):
				g['s'] = neither_fc[s]
			if len(g.keys()) == 0:
				break
			to_increment = min(g, key=g.get)
			if to_increment == 'q':
				q += 1
			if to_increment == 'r':
				r += 1
			if to_increment == 's':
				s += 1
		if p + q + r + s < M:
			break
		while p + q + r + s > M:
			g = dict()
			if 0 < q and p + q > K:
				g['q'] = alice_only_fc[q - 1]
			if 0 < r and p + r > K:
				g['r'] = bob_only_fc[r - 1]
			if 0 < s:
				g['s'] = neither_fc[s - 1]
			if len(g.keys()) == 0:
				break
			to_decrement = max(g, key=g.get)
			if to_decrement == 'q':
				q -= 1
			if to_decrement == 'r':
				r -= 1
			if to_decrement == 's':
				s -= 1
		if p + q + r + s > M:
			break
		score = both_prefix[p] + alice_only_prefix[q] + bob_only_prefix[r] + neither_prefix[s]
		if score < best_score:
			best_score = score
			best_pqrs = (p, q, r, s)
	(p, q, r, s) = best_pqrs
	ret_array = []
	for i in range(p):
		ret_array += [both[i][1]]
	for i in range(q):
		ret_array += [alice_only[i][1]]
	for i in range(r):
		ret_array += [bob_only[i][1]]
	for i in range(s):
		ret_array += [neither[i][1]]
	return (best_score, ret_array)
(N, M, K) = input().split(' ')
N = int(N)
K = int(K)
M = int(M)
alice_only = []
bob_only = []
both = []
neither = []
inorder = []
for i in range(1, N + 1):
	(t, a, b) = input().split(' ')
	t = int(t)
	a = int(a)
	b = int(b)
	if a == 0 and b == 0:
		neither += [(t, i)]
	if a == 1 and b == 1:
		both += [(t, i)]
	if a == 1 and b == 0:
		alice_only += [(t, i)]
	if a == 0 and b == 1:
		bob_only += [(t, i)]
	inorder += [t]
alice_only = sorted(alice_only)
bob_only = sorted(bob_only)
both = sorted(both)
neither = sorted(neither)
ret = ans(both, alice_only, bob_only, neither, M, K)
if ret is None:
	print(-1)
else:
	(a, b) = ret
	print(a)
	print(' '.join(map(str, b)))
	check = 0
	for idx in b:
		check += inorder[idx - 1]
	assert a == check


import sys
input = sys.stdin.readline

def main():
	(n, k) = map(int, input().split())
	(A, B, C) = ([], [], [])
	for i in range(n):
		(n, a, b) = map(int, input().split())
		if a == 1 and b == 1:
			A.append(n)
		elif a == 1 and b == 0:
			B.append(n)
		elif a == 0 and b == 1:
			C.append(n)
	B.sort()
	C.sort()
	v = min(len(B), len(C))
	for i in range(v):
		A.append(B[i] + C[i])
	if len(A) < k:
		print(-1)
	else:
		A.sort()
		ans = 0
		for i in range(k):
			ans = ans + A[i]
		print(ans)
main()


(n, k) = map(int, input().split())
t = []
a = []
b = []
an = k
bn = k
for i in range(n):
	(t1, a1, b1) = map(int, input().split())
	t.append(t1)
	a.append(a1)
	b.append(b1)
both_like = []
a_like = []
b_like = []
for i in range(n):
	if a[i] == 1 and b[i] == 1:
		both_like.append(t[i])
	elif a[i] == 1 and b[i] == 0:
		a_like.append(t[i])
	elif a[i] == 0 and b[i] == 1:
		b_like.append(t[i])
both_like.sort()
a_like.sort()
b_like.sort()
ans = 0
i = 0
j = 0
k = 0
while i < len(both_like) and an > 0 and (bn > 0):
	if j < len(a_like) and k < len(b_like) and (both_like[i] >= a_like[j] + b_like[k]):
		ans += a_like[j] + b_like[k]
		j += 1
		k += 1
		an -= 1
		bn -= 1
	else:
		ans += both_like[i]
		i += 1
		an -= 1
		bn -= 1
while an > 0 and j < len(a_like):
	ans += a_like[j]
	j += 1
	an -= 1
while bn > 0 and k < len(b_like):
	ans += b_like[k]
	k += 1
	bn -= 1
if an == 0 and bn == 0:
	print(ans)
else:
	print(-1)


(book_number, like_num) = map(int, input().split())
both_like = []
only_alice = []
only_bob = []
for _ in range(book_number):
	(t, a, b) = map(int, input().split())
	if a == b == 1:
		both_like.append(t)
	elif a == 1:
		only_alice.append(t)
	elif b == 1:
		only_bob.append(t)
(i, j) = (0, 0)
time = 0
current_like = 0
both_like.sort()
only_alice.sort()
only_bob.sort()
while current_like < like_num:
	if i < len(both_like) and j < min(len(only_alice), len(only_bob)):
		if both_like[i] < only_alice[j] + only_bob[j]:
			time += both_like[i]
			i += 1
		else:
			time += only_alice[j] + only_bob[j]
			j += 1
		current_like += 1
	elif i < len(both_like):
		time += both_like[i]
		i += 1
		current_like += 1
	elif j < min(len(only_alice), len(only_bob)):
		time += only_alice[j] + only_bob[j]
		j += 1
		current_like += 1
	else:
		break
if current_like == like_num:
	print(time)
else:
	print(-1)


def main():
	(n, k) = map(int, input().split())
	alice_counter = k
	bob_counter = k
	total_time = 0
	both = []
	alice = []
	bob = []
	for _ in range(n):
		(t, a, b) = map(int, input().split())
		if a and b:
			both.append(t)
		elif a:
			alice.append(t)
		elif b:
			bob.append(t)
	both = sorted(both)
	alice = sorted(alice)
	bob = sorted(bob)
	pointer = [0] * 3
	while True:
		if bob_counter == 0 and alice_counter == 0:
			return total_time
		if pointer[1] >= len(alice) or pointer[2] >= len(bob):
			while bob_counter > 0 or alice_counter > 0:
				if pointer[0] >= len(both):
					return -1
				total_time += both[pointer[0]]
				pointer[0] += 1
				bob_counter -= 1
				alice_counter -= 1
			return total_time
		elif pointer[0] >= len(both):
			while bob_counter > 0 or alice_counter > 0:
				if pointer[1] >= len(alice) or pointer[2] >= len(bob):
					return -1
				total_time += alice[pointer[1]] + bob[pointer[2]]
				pointer[1] += 1
				pointer[2] += 1
				bob_counter -= 1
				alice_counter -= 1
			return total_time
		else:
			if both[pointer[0]] > alice[pointer[1]] + bob[pointer[2]]:
				total_time += alice[pointer[1]] + bob[pointer[2]]
				pointer[1] += 1
				pointer[2] += 1
			else:
				total_time += both[pointer[0]]
				pointer[0] += 1
			bob_counter -= 1
			alice_counter -= 1
print(main())


(n, k) = map(int, input().split())
share = []
alice = []
bob = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a and b:
		share.append(t)
	elif a:
		alice.append(t)
	elif b:
		bob.append(t)
share.sort()
cs = [0]
for i in share:
	cs.append(cs[-1] + i)
alice.sort()
ca = [0]
for i in alice:
	ca.append(ca[-1] + i)
bob.sort()
cb = [0]
for i in bob:
	cb.append(cb[-1] + i)
an = float('INF')
for i in range(min(len(share), k) + 1):
	if len(alice) >= k - i and len(bob) >= k - i:
		an = min(an, cs[i] + ca[k - i] + cb[k - i])
if an == float('INF'):
	print(-1)
else:
	print(an)


import itertools

def good(combo, k):
	alice = 0
	bob = 0
	for (t, a, b) in combo:
		if a == 1:
			alice += 1
		if b == 1:
			bob += 1
	return alice >= k and bob >= k

def brute(arr, k):
	result = float('inf')
	for comboSize in range(len(arr) - 1, 0, -1):
		for combo in itertools.combinations(arr, comboSize):
			if good(combo, k):
				curr = sum((t for (t, _, _) in combo))
				if curr < result:
					result = curr
	if result == float('inf'):
		return -1
	return result

def fast(arr, k):
	anums = []
	bnums = []
	cnums = []
	for (t, a, b) in arr:
		if a == 1 and b == 0:
			anums.append(t)
		elif a == 0 and b == 1:
			bnums.append(t)
		elif a == 1 and b == 1:
			cnums.append(t)
	anums.sort()
	bnums.sort()
	cnums.sort()
	result = 0
	(a, b, c) = (0, 0, 0)
	alice = 0
	bob = 0
	while alice < k and bob < k:
		if a < len(anums) and b < len(bnums):
			up1 = anums[a] + bnums[b]
		else:
			up1 = float('inf')
		if c < len(cnums):
			up2 = cnums[c]
		else:
			up2 = float('inf')
		if up1 == float('inf') and up2 == float('inf'):
			return -1
		if up1 < up2:
			a += 1
			b += 1
			result += up1
		else:
			c += 1
			result += up2
		alice += 1
		bob += 1
	return result

def main():
	(n, k) = [int(x) for x in input().split()]
	arr = []
	for _ in range(n):
		(t, a, b) = [int(x) for x in input().split()]
		arr.append((t, a, b))
	result = fast(arr, k)
	print(result)
main()


from collections import Counter, defaultdict, deque
import sys
input = sys.stdin.readline

def primes(n):
	i = 2
	factors = []
	while i * i <= n:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return factors

def solve():
	(n, k) = [int(x) for x in input().split()]
	onlya = []
	onlyb = []
	both = []
	for i in range(n):
		(t, a, b) = [int(x) for x in input().split()]
		if a and b:
			both.append(t)
		elif b:
			onlyb.append(t)
		elif a:
			onlya.append(t)
	onlya = deque(sorted(onlya))
	both = deque(sorted(both))
	onlyb = deque(sorted(onlyb))
	ans = 0
	for i in range(k):
		if len(both) == 0 and len(onlya) * len(onlyb) == 0:
			print(-1)
			return
		if not len(onlya) * len(onlyb) or (len(both) and both[0] <= onlya[0] + onlyb[0]):
			ans += both.popleft()
		else:
			if len(onlya) * len(onlyb) == 0:
				print(-1)
				return
			ans += onlya.popleft()
			ans += onlyb.popleft()
	print(ans)
tt = 1
for test in range(tt):
	solve()


import sys

def input():
	return sys.stdin.readline().rstrip()

def input_split():
	return [int(i) for i in input().split()]

def add_book():
	global freqs, cf, cp
	while True:
		if cf < freqs[cp]:
			cf += 1
			return cp
		else:
			cp += 1
			cf = 0

def remove_book():
	global freqs, cf, cp
	while True:
		if cf > 0:
			cf -= 1
			return -cp
		else:
			cp -= 1
			cf = freqs[cp]

def make_available(b_time):
	global freqs, cf, cp
	freqs[b_time] += 1
	if b_time < cp:
		return b_time + remove_book()
	else:
		return 0

def make_unavailable(b_time):
	global freqs, cf, cp
	if b_time < cp:
		freqs[b_time] -= 1
		return -b_time + add_book()
	elif b_time == cp and cf == freqs[cp]:
		freqs[b_time] -= 1
		cf -= 1
		return -b_time + add_book()
	else:
		freqs[b_time] -= 1
		return 0
(n, m, k) = input_split()
times = []
alice_likes = []
bob_likes = []
for _ in range(n):
	(t, a, b) = input_split()
	times.append(t)
	alice_likes.append(a)
	bob_likes.append(b)
times_both = []
times_alice = []
times_bob = []
times_none = []
for book in range(n):
	if alice_likes[book] == 1 and bob_likes[book] == 1:
		times_both.append((times[book], book))
	elif alice_likes[book] == 1:
		times_alice.append((times[book], book))
	elif bob_likes[book] == 1:
		times_bob.append((times[book], book))
	else:
		times_none.append((times[book], book))
times_both.sort()
times_alice.sort()
times_bob.sort()
started = False
possibilities = []
for i in range(k + 1):
	both = i
	indi = k - i
	extra = m - (both + 2 * indi)
	if both > len(times_both) or indi > min(len(times_alice), len(times_bob)) or extra < 0:
		continue
	if not started:
		started = True
		ans = sum([i for (i, j) in times_both[:both]])
		ans += sum([i for (i, j) in times_alice[:indi]])
		ans += sum([i for (i, j) in times_bob[:indi]])
		freqs = [0 for i in range(10001)]
		pending = times_both[both:] + times_bob[indi:] + times_alice[indi:] + times_none
		for (tim, _) in pending:
			freqs[tim] += 1
		cp = 0
		cf = 0
		extra_cost = 0
		count = 0
		for _ in range(extra):
			extra_cost += add_book()
		ans += extra_cost
		possibilities.append((ans, both))
	else:
		last_ans = possibilities[-1][0]
		ans = last_ans
		new_book1_time = times_alice[indi][0]
		new_book2_time = times_bob[indi][0]
		old_book_time = times_both[both - 1][0]
		ans += old_book_time
		ans -= new_book1_time
		ans -= new_book2_time
		ans += make_available(new_book1_time)
		ans += make_available(new_book2_time)
		ans += make_unavailable(old_book_time)
		ans += add_book()
		possibilities.append((ans, both))
if len(possibilities) == 0:
	print(-1)
else:
	(ans, both) = min(possibilities)
	indi = k - both
	extra = m - (indi * 2 + both)
	books = []
	books += [j for (i, j) in times_both[:both]]
	books += [j for (i, j) in times_alice[:indi]]
	books += [j for (i, j) in times_bob[:indi]]
	pending = times_both[both:] + times_bob[indi:] + times_alice[indi:] + times_none
	pending.sort()
	books += [j for (i, j) in pending[:extra]]
	books = [b + 1 for b in books]
	print(ans)
	print(*books, sep=' ')


def abc(l, n, i, x, y, m, k):
	if x >= k and y >= k:
		return m
	if i == n:
		return -1
	ans = -1
	ans = abc(l, n, i + 1, x, y, m, k)
	c = abc(l, n, i + 1, x + l[i][1], y + l[i][2], m + l[i][0], k)
	if c != -1:
		if ans == -1:
			ans = c
		else:
			ans = min(ans, c)
	return ans
(n, k) = map(int, input().split())
l = []
for i in range(n):
	l.append(list(map(int, input().split())))
d = {}
d[0, 0] = []
d[0, 1] = []
d[1, 0] = []
d[1, 1] = []
for i in l:
	d[i[1], i[2]] += [i[0]]
for i in d:
	d[i] = sorted(d[i], reverse=True)
ans = 0
while k > 0:
	if len(d[1, 1]) == 0:
		if len(d[0, 1]) == 0 or len(d[1, 0]) == 0:
			break
		ans += d[0, 1][-1] + d[1, 0][-1]
		del d[0, 1][-1]
		del d[1, 0][-1]
		k -= 1
	elif len(d[0, 1]) == 0 or len(d[1, 0]) == 0:
		ans += d[1, 1][-1]
		del d[1, 1][-1]
		k -= 1
	else:
		x = d[0, 1][-1] + d[1, 0][-1]
		if x <= d[1, 1][-1]:
			ans += d[0, 1][-1] + d[1, 0][-1]
			del d[0, 1][-1]
			del d[1, 0][-1]
			k -= 1
		else:
			ans += d[1, 1][-1]
			del d[1, 1][-1]
			k -= 1
if k == 0:
	print(ans)
else:
	print(-1)


(n, k) = map(int, input().split())
(a, b, ab) = ([], [], [])
for _ in range(n):
	(it, ia, ib) = map(int, input().split())
	if ia == 1 and ib == 1:
		ab.append(it)
	elif ia == 1:
		a.append(it)
	elif ib == 1:
		b.append(it)
a.sort()
b.sort()
nab = [i + j for (i, j) in zip(a[:min(len(a) + 1, len(b) + 1)], b[:min(len(a) + 1, len(b) + 1)])]
fab = ab + nab
fab.sort()
print(sum(fab[:k]) if k <= len(fab) else -1)


(n, k1) = map(int, input().split())
A = []
B = []
AB = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		AB.append(t)
	elif a == 1:
		A.append(t)
	elif b == 1:
		B.append(t)
AB.sort()
A.sort()
B.sort()
if len(AB) + len(A) >= k1 and len(AB) + len(B) >= k1:
	a = 0
	b = 0
	i = 0
	j = 0
	k = 0
	ans = 0
	books = 0
	while i < len(A) and j < len(B) and (k < len(AB)):
		if A[i] + B[j] <= AB[k]:
			ans += A[i] + B[j]
			i += 1
			j += 1
			books += 1
		else:
			ans += AB[k]
			k += 1
			books += 1
		if books == k1:
			break
	if i >= len(A) and books != k1:
		ans += sum(AB[k:k + k1 - books])
	elif j >= len(B) and books != k1:
		ans += sum(AB[k:k + k1 - books])
	elif k >= len(AB) and books != k1:
		ans += sum(A[i:i + k1 - books]) + sum(B[j:j + k1 - books])
	print(ans)
else:
	print(-1)


first_nums = input().split()
len_matris = int(first_nums[0])
k = int(first_nums[1])
books = []
for i in range(len_matris):
	book = input().split()
	books.append([int(x) for x in book])
liked_books = list(filter(lambda x: x[1] == 1 and x[2] == 1, books))
books_0_1 = list(filter(lambda x: x[1] == 0 and x[2] == 1, books))
books_1_0 = list(filter(lambda x: x[1] == 1 and x[2] == 0, books))
books_0_1.sort()
books_1_0.sort()
liked_books.sort()
result_books = []
for i in liked_books:
	result_books.append(i[0])
for (a, b) in zip(books_1_0, books_0_1):
	result_books.append(a[0] + b[0])
result_books.sort()
if len(books_1_0) + len(liked_books) < k or len(books_0_1) + len(liked_books) < k:
	print(-1)
else:
	print(sum(result_books[:k]))


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def solve():
	(n, k) = map(int, input().split())
	books = []
	for i in range(n):
		(t, a, b) = map(int, input().split())
		books.append((t, a == 1, b == 1))
	books_everybody_like = []
	books_alice_like = []
	books_bob_like = []
	for b in books:
		if b[1] and b[2]:
			books_everybody_like.append(b)
		elif b[1]:
			books_alice_like.append(b)
		elif b[2]:
			books_bob_like.append(b)
	books_alice_like = sorted(books_alice_like, key=lambda x: x[0])
	books_bob_like = sorted(books_bob_like, key=lambda x: x[0])
	for (a, b) in zip(books_alice_like, books_bob_like):
		books_everybody_like.append((a[0] + b[0], True, True))
	if len(books_everybody_like) < k:
		print(-1)
		return
	books_everybody_like = sorted(books_everybody_like, key=lambda x: x[0])
	answer = 0
	for i in range(k):
		answer += books_everybody_like[i][0]
	print(answer)
solve()


s = input()
s1 = s.split()
n = int(s1[0])
k = int(s1[1])
import heapq
heap1 = []
heap2 = []
heap3 = []
heapq.heapify(heap1)
heapq.heapify(heap2)
heapq.heapify(heap3)
for i in range(n):
	s = input()
	s1 = s.split()
	if int(s1[1]) == 0 and int(s1[2]) == 1:
		heapq.heappush(heap1, int(s1[0]))
	if int(s1[1]) == 1 and int(s1[2]) == 0:
		heapq.heappush(heap2, int(s1[0]))
	if int(s1[1]) == 1 and int(s1[2]) == 1:
		heapq.heappush(heap3, int(s1[0]))
sum1 = 0
while (heap1 and heap2 or heap3) and k > 0:
	if heap1 and heap2:
		c1 = heapq.heappop(heap1)
		c2 = heapq.heappop(heap2)
	else:
		c1 = 10000000000.0
		c2 = 10000000000.0
	if heap3:
		c3 = heapq.heappop(heap3)
	else:
		c3 = 10000000000.0
	if c3 < c2 + c1:
		sum1 = sum1 + c3
		if c1 != 10000000000.0:
			heapq.heappush(heap1, c1)
		if c2 != 10000000000.0:
			heapq.heappush(heap2, c2)
	else:
		sum1 = sum1 + c2 + c1
		if c3 != 10000000000.0:
			heapq.heappush(heap3, c3)
	k = k - 1
if k > 0:
	print(-1)
else:
	print(sum1)


(n, k) = map(int, input().split())
tab = [list(map(int, input().split())) for _ in range(n)]
x = []
y = []
z = []
for i in range(n):
	if tab[i][1] == tab[i][2] == 1:
		x.append(tab[i])
	elif tab[i][1] == 1:
		y.append(tab[i])
	elif tab[i][2] == 1:
		z.append(tab[i])
x.sort()
y.sort()
z.sort()
sx = [0] * (len(x) + 1)
sy = [0] * (len(y) + 1)
sz = [0] * (len(z) + 1)
for i in range(1, len(x) + 1):
	sx[i] = x[i - 1][0]
for i in range(1, len(y) + 1):
	sy[i] = y[i - 1][0]
for i in range(1, len(z) + 1):
	sz[i] = z[i - 1][0]
for i in range(1, len(sx)):
	sx[i] += sx[i - 1]
for i in range(1, len(sy)):
	sy[i] += sy[i - 1]
for i in range(1, len(sz)):
	sz[i] += sz[i - 1]
ans = 10 ** 18
for i in range(k + 1):
	if not (0 <= i <= len(x) and 0 <= k - i <= len(y) and (0 <= k - i <= len(z))):
		continue
	res = sx[i] + sy[k - i] + sz[k - i]
	ans = min(ans, res)
if ans == 10 ** 18:
	print(-1)
else:
	print(ans)


import sys
from collections import deque
reader = (tuple(map(int, line.split())) for line in sys.stdin)
(both, alice, bob) = ([], [], [])
(n, k) = next(reader)
for _ in range(n):
	(value, alice_fl, bob_fl) = next(reader)
	if alice_fl and bob_fl:
		both.append(value)
	if alice_fl and (not bob_fl):
		alice.append(value)
	if not alice_fl and bob_fl:
		bob.append(value)
both.sort()
both = deque(both)
alice.sort()
alice = deque(alice)
bob.sort()
bob = deque(bob)
(cnt_alice, cnt_bob) = (0, 0)
result = 0
while cnt_alice < k and cnt_bob < k:
	if len(both) > 0 and len(alice) > 0 and (len(bob) > 0):
		if both[0] <= alice[0] + bob[0]:
			result += both.popleft()
		else:
			result += alice.popleft() + bob.popleft()
		cnt_alice += 1
		cnt_bob += 1
	elif len(alice) == 0 or len(bob) == 0:
		if len(both) > 0:
			result += both.popleft()
			cnt_alice += 1
			cnt_bob += 1
		else:
			result = -1
			break
	else:
		result += alice.popleft()
		result += bob.popleft()
		cnt_alice += 1
		cnt_bob += 1
print(result)


(n, k) = map(int, input().split())
(aa, bb, cc) = ([0], [0], [0])
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == b and a == 1:
		cc.append(t)
	elif a == 1:
		aa.append(t)
	elif b == 1:
		bb.append(t)
aa.sort()
bb.sort()
cc.sort()
for i in range(1, len(aa)):
	aa[i] = aa[i - 1] + aa[i]
for i in range(1, len(bb)):
	bb[i] = bb[i - 1] + bb[i]
for i in range(1, len(cc)):
	cc[i] = cc[i - 1] + cc[i]
if len(cc) + len(bb) < k + 2 or len(cc) + len(aa) < k + 2:
	print(-1)
else:
	ans = float('inf')
	for i in range(max(0, k - min(len(aa) - 1, len(bb) - 1)), min(len(cc), k + 1)):
		ans = min(ans, cc[i] + bb[k - i] + aa[k - i])
	print(ans)


(n, k) = map(int, input().split())
l = []
al = []
bl = []
ac = bc = 0
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		l.append(t)
		ac += 1
		bc += 1
	elif a == 1:
		al.append(t)
		ac += 1
	elif b == 1:
		bl.append(t)
		bc += 1
if ac < k or bc < k:
	print('-1')
else:
	al.sort()
	bl.sort()
	i = 0
	while i < len(al) and i < len(bl):
		l.append(al[i] + bl[i])
		i += 1
	l.sort()
	time = 0
	for i in range(k):
		time += l[i]
	print(time)


(n, k) = map(int, input().split())
books = [list(map(int, input().split())) for i in range(n)]
(AB, A, B) = ([[10 ** 5, 0, 0]], [[10 ** 5, 0, 0]], [[10 ** 5, 0, 0]])
for (t, a, b) in books:
	if a == 1 and b == 1:
		AB.append([t, a, b])
	elif a == 1 and b == 0:
		A.append([t, a, b])
	elif a == 0 and b == 1:
		B.append([t, a, b])
AB = list(reversed(sorted(AB)))
A = list(reversed(sorted(A)))
B = list(reversed(sorted(B)))
ans = []
for i in range(k):
	if len(AB) != 1 and AB[-1][0] < A[-1][0] + B[-1][0]:
		ans.append(AB.pop()[0])
	elif len(A) != 1 and len(B) != 1:
		ans.append(A.pop()[0])
		ans.append(B.pop()[0])
	else:
		print(-1)
		break
else:
	print(sum(ans))


(n, m, k) = map(int, input().split())
bookA = []
bookB = []
bookAB = []
book = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		bookAB.append((t, i))
	elif a == 1:
		bookA.append((t, i))
		book.append((t, i))
	elif b == 1:
		bookB.append((t, i))
		book.append((t, i))
	else:
		book.append((t, i))
bookA.sort(key=lambda x: x[0])
bookB.sort(key=lambda x: x[0])
bookAB.sort(key=lambda x: x[0])
book.sort(key=lambda x: x[0])
bookAIndex = 0
bookBIndex = 0
bookALocation = []
bookBLocation = []
for i in range(len(book)):
	if bookAIndex < len(bookA) and bookA[bookAIndex] == book[i]:
		bookALocation.append(i)
		bookAIndex += 1
	if bookBIndex < len(bookB) and bookB[bookBIndex] == book[i]:
		bookBLocation.append(i)
		bookBIndex += 1
bookACount = 0
bookBCount = 0
bookCount = [(0, 0)]
for i in range(len(book)):
	if bookACount < len(bookALocation) and bookALocation[bookACount] == i:
		bookACount += 1
	if bookBCount < len(bookBLocation) and bookBLocation[bookBCount] == i:
		bookBCount += 1
	bookCount.append((bookACount, bookBCount))
bookASum = [0]
bookBSum = [0]
bookABSum = [0]
bookSum = [0]
for elem in bookA:
	bookASum.append(bookASum[-1] + elem[0])
for elem in bookB:
	bookBSum.append(bookBSum[-1] + elem[0])
for elem in bookAB:
	bookABSum.append(bookABSum[-1] + elem[0])
for elem in book:
	bookSum.append(bookSum[-1] + elem[0])
minReadingTime = -1
for i in range(len(bookABSum)):
	if len(bookA) >= k - i and len(bookB) >= k - i and (2 * k - i <= m) and (m >= i):
		goalbookCount = m - i - 2 * max(k - i, 0)
		high = len(book)
		low = goalbookCount
		isPossible = True
		while True:
			if high < low:
				isPossible = False
				break
			mid = (high + low) // 2
			curBookCount = mid - min(max(k - i, 0), bookCount[mid][0]) - min(max(k - i, 0), bookCount[mid][1])
			if curBookCount == goalbookCount:
				if high == low:
					break
				high = mid
			elif high == low:
				isPossible = False
				break
			elif curBookCount > goalbookCount:
				high = mid - 1
			else:
				low = mid + 1
		if isPossible and (minReadingTime == -1 or minReadingTime > bookABSum[i] + bookASum[max(k - i, 0)] + bookBSum[max(k - i, 0)] + bookSum[mid] - bookASum[min(max(k - i, 0), bookCount[mid][0])] - bookBSum[min(max(k - i, 0), bookCount[mid][1])]):
			minReadingTime = bookABSum[i] + bookASum[max(k - i, 0)] + bookBSum[max(k - i, 0)] + bookSum[mid] - bookASum[min(max(k - i, 0), bookCount[mid][0])] - bookBSum[min(max(k - i, 0), bookCount[mid][1])]
			minIndicies = (i, max(k - i, 0), mid, min(max(k - i, 0), bookCount[mid][0]), min(max(k - i, 0), bookCount[mid][1]))
print(minReadingTime)
printList = []
if minReadingTime != -1:
	for i in range(minIndicies[0]):
		printList.append(str(bookAB[i][1] + 1))
	for i in range(minIndicies[2]):
		printList.append(str(book[i][1] + 1))
	for i in range(minIndicies[3], minIndicies[1]):
		printList.append(str(bookA[i][1] + 1))
	for i in range(minIndicies[4], minIndicies[1]):
		printList.append(str(bookB[i][1] + 1))
print(' '.join(printList))


(n, k) = list(map(int, input().split()))
ali = []
bob = []
both = []
(ac, bc) = (0, 0)
for __ in range(n):
	(t, ai, bi) = list(map(int, input().split()))
	if ai == bi and ai == 1:
		both.append(t)
		ac += 1
		bc += 1
	elif ai == 1:
		ali.append(t)
		ac += 1
	elif bi == 1:
		bob.append(t)
		bc += 1
if ac < k or bc < k:
	print(-1)
else:
	ans = 0
	i = 0
	both.sort()
	ali.sort()
	bob.sort()
	bbi = 0
	(ai, bi) = (0, 0)
	bbl = len(both)
	al = len(ali)
	bl = len(bob)
	while i < k:
		if bbi < bbl and ai < al and (bi < bl):
			age = both[bbi]
			pic = ali[ai] + bob[bi]
			if age < pic:
				ans += age
				bbi += 1
			else:
				ans += pic
				ai += 1
				bi += 1
		elif bbi < bbl:
			ans += both[bbi]
			bbi += 1
		else:
			ans += ali[ai] + bob[bi]
			ai += 1
			bi += 1
		i += 1
	print(ans)


(n, k) = map(int, input().split())
(z11, z01, z10) = ([], [], [])
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		z11.append(t)
	elif a == 1:
		z10.append(t)
	elif b == 1:
		z01.append(t)
(i, j) = (min(k, len(z11)), min(k, len(z01), len(z10)))
z11.sort()
z10.sort()
z01.sort()
if i + j < k:
	print(-1)
	exit()
while i + j > k:
	if z11[i - 1] > z10[j - 1] + z01[j - 1]:
		i -= 1
	else:
		j -= 1
print(sum(z11[:i]) + sum(z10[:j]) + sum(z01[:j]))


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
alice = []
bob = []
both = []
for _ in range(n):
	r = list(map(int, input().split()))
	if r[1] == 1 and r[2] == 0:
		alice.append(r[0])
	elif r[1] == 0 and r[2] == 1:
		bob.append(r[0])
	elif r[1] == 1 and r[2] == 1:
		both.append(r[0])
alice.sort()
bob.sort()
if len(both) + min(len(alice), len(bob)) >= k:
	for i in range(min(len(alice), len(bob))):
		both.append(alice[i] + bob[i])
	both.sort()
	print(sum(both[:k]))
else:
	print(-1)


(n, k) = map(int, input().split())
l1 = []
l2 = []
l3 = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if (a, b) == (1, 1):
		l3.append(t)
	elif (a, b) == (0, 1):
		l1.append(t)
	elif (a, b) == (1, 0):
		l2.append(t)
s = 0
l1.sort()
l2.sort()
l3.sort()
if len(l3) >= k:
	s = sum(l3[:k])
	p = 0
	p1 = k - 1
else:
	s = sum(l3)
	v = k - len(l3)
	if len(l1) >= v and len(l2) >= v:
		s += sum(l1[:v]) + sum(l2[:v])
	else:
		print(-1)
		exit()
	p = v
	p1 = len(l3) - 1
while p < len(l1) and p < len(l2) and (p1 >= 0):
	if l1[p] + l2[p] <= l3[p1]:
		s = s - l3[p1] + l1[p] + l2[p]
		p1 -= 1
		p += 1
	else:
		break
print(s)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
sys.setrecursionlimit(int(pow(10, 6)))
mod = int(pow(10, 9) + 7)
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
t = 1
for _ in range(t):
	(n, k) = l()
	A = [[], [], []]
	bc = 0
	ac = 0
	for i in range(n):
		(a, b, c) = l()
		if b == c and b == 1:
			A[0].append(a)
		elif b == 1 and c == 0:
			A[1].append(a)
		elif b == 0 and c == 1:
			A[2].append(a)
	A[0].sort()
	A[1].sort()
	A[2].sort()
	for i in range(1, len(A[0])):
		A[0][i] += A[0][i - 1]
	for i in range(1, len(A[1])):
		A[1][i] += A[1][i - 1]
	for i in range(1, len(A[2])):
		A[2][i] += A[2][i - 1]
	time = 10 ** 10
	A[0] = [0] + A[0]
	A[1] = [0] + A[1]
	A[2] = [0] + A[2]
	for cnt in range(len(A[0])):
		try:
			time = min(time, A[0][cnt] + A[1][k - cnt] + A[2][k - cnt])
		except:
			continue
	if time == 10 ** 10:
		print(-1)
	else:
		print(time)


(n, k) = [int(i) for i in input().split()]
a_likes = list()
b_likes = list()
both_like = list()
a_likes.append(0)
b_likes.append(0)
both_like.append(0)
for book in range(n):
	(t, a, b) = [int(i) for i in input().split()]
	if a == 1 and b == 1:
		both_like.append(t)
	elif a == 1:
		a_likes.append(t)
	elif b == 1:
		b_likes.append(t)
a_likes.sort()
b_likes.sort()
both_like.sort()
for i in range(1, len(a_likes)):
	a_likes[i] += a_likes[i - 1]
for i in range(1, len(b_likes)):
	b_likes[i] += b_likes[i - 1]
for i in range(1, len(both_like)):
	both_like[i] += both_like[i - 1]
if len(both_like) + len(a_likes) < k or len(both_like) + len(b_likes) < k:
	print('-1')
else:
	ans = 2 * pow(10, 9) + 1
	rbo = 0
	while rbo < min(len(both_like), k + 1):
		if k - rbo < len(a_likes) and k - rbo < len(b_likes):
			ans = min(ans, both_like[rbo] + a_likes[k - rbo] + b_likes[k - rbo])
		rbo += 1
	if ans < 2 * pow(10, 9) + 1:
		print(ans)
	else:
		print('-1')


from sys import stdin, stdout
input = stdin.readline
print = stdout.write
(n, k) = map(int, input().split())
(alice, bob, together) = ([], [], [])
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a and b:
		together += (t,)
	elif a:
		alice += (t,)
	elif b:
		bob += (t,)
(sa, sb, st) = (len(alice), len(bob), len(together))
if sa + st < k or sb + st < k:
	print('-1')
	exit()
sa -= 1
sb -= 1
st -= 1
alice.sort(reverse=True)
bob.sort(reverse=True)
together.sort(reverse=True)
time = 0
for i in range(k):
	if sa < 0 or sb < 0:
		time += together[st]
		st -= 1
	elif st < 0:
		time += alice[sa] + bob[sb]
		sa -= 1
		sb -= 1
	elif together[st] <= alice[sa] + bob[sb]:
		time += together[st]
		st -= 1
	else:
		time += alice[sa] + bob[sb]
		sa -= 1
		sb -= 1
print(str(time))


from sys import maxsize
(n, k) = map(int, input().split())
l = [[0], [0], [0], [0]]
x = []
ans = maxsize
for i in range(n):
	x.append(list(map(int, input().split())))
x.sort()
for p in x:
	temp = l[p[1] * 2 + p[2]][-1]
	l[p[1] * 2 + p[2]].append(temp + p[0])
for i in range(min(k + 1, len(l[3]))):
	if k - i < len(l[1]) and k - i < len(l[2]):
		ans = min(ans, l[3][i] + l[1][k - i] + l[2][k - i])
if ans == maxsize:
	print(-1)
else:
	print(ans)


(n, K) = list(map(int, input().split()))
l = [list(map(int, input().split())) for _ in range(n)]
(al, bo, bt) = ([], [], [])
for i in l:
	if i[1] == 1 and i[2] == 1:
		bt.append(i[0])
	elif i[1] == 1 and i[2] == 0:
		al.append(i[0])
	elif i[1] == 0 and i[2] == 1:
		bo.append(i[0])
al.sort()
bt.sort()
bo.sort()
(i, j, k) = (0, 0, 0)
(ans, cnt) = (0, 0)
while i < len(al) and j < len(bo) and (k < len(bt)) and (cnt < K):
	if al[i] + bo[j] < bt[k]:
		ans += al[i] + bo[j]
		i += 1
		j += 1
	else:
		ans += bt[k]
		k += 1
	cnt += 1
while k < len(bt) and cnt < K:
	ans += bt[k]
	k += 1
	cnt += 1
while cnt < K and i < len(al) and (j < len(bo)):
	ans += al[i] + bo[j]
	i += 1
	j += 1
	cnt += 1
if cnt < K:
	print(-1)
else:
	print(ans)


import sys
(n, k) = map(int, input().split())
a = []
b = []
g = []
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x and y:
		a.append(t)
	elif x:
		g.append(t)
	elif y:
		b.append(t)
a.sort()
b.sort()
g.sort()
t = 0
i = 0
j = 0
for o in range(k):
	if i < len(a) and j < min(len(b), len(g)):
		if a[i] < g[j] + b[j]:
			t += a[i]
			i += 1
		else:
			t += g[j] + b[j]
			j += 1
	elif i < len(a):
		t += a[i]
		i += 1
	elif j < min(len(b), len(g)):
		t += g[j] + b[j]
		j += 1
	else:
		print(-1)
		sys.exit(0)
print(t)


(n, k) = map(int, input().split())
main = []
for i in range(n):
	l = list(map(int, input().split()))
	main.append(l)
list01 = []
list10 = []
list11 = []
for i in main:
	if i[1] == 0 and i[2] == 1:
		list01.append(i)
	elif i[1] == 1 and i[2] == 0:
		list10.append(i)
	elif i[1] == 1 and i[2] == 1:
		list11.append(i)
list01.sort()
list10.sort()
newlist11 = []
l1 = len(list01)
l2 = len(list10)
sum = 0
for i in range(0, min(l1, l2)):
	sum = list01[i][0] + list10[i][0]
	newlist11.append([sum, 1, 1])
finallist = []
finallist = list11 + newlist11
finallist.sort()
add = 0
if len(finallist) < k:
	print(-1)
else:
	for i in range(0, k):
		add += finallist[i][0]
	print(add)


import sys

def input():
	return sys.stdin.readline().rstrip()

def input_split():
	return [int(i) for i in input().split()]
(n, k) = input_split()
times = []
alice_likes = []
bob_likes = []
for _ in range(n):
	(t, a, b) = input_split()
	times.append(t)
	alice_likes.append(a)
	bob_likes.append(b)
if sum(alice_likes) < k or sum(bob_likes) < k:
	ans = -1
else:
	times_both = []
	times_alice = []
	times_bob = []
	for book in range(n):
		if alice_likes[book] == 1 and bob_likes[book] == 1:
			times_both.append(times[book])
		elif alice_likes[book] == 1:
			times_alice.append(times[book])
		elif bob_likes[book] == 1:
			times_bob.append(times[book])
		else:
			pass
	times_both.sort()
	times_alice.sort()
	times_bob.sort()
	times_both = times_both + [100000] * (n - len(times_both))
	times_alice = times_alice + [100000] * (n - len(times_alice))
	times_bob = times_bob + [100000] * (n - len(times_bob))
	ans = 0
	(p1, p2, p3) = (0, 0, 0)
	for i in range(k):
		if times_both[p1] <= times_alice[p2] + times_bob[p3]:
			ans += times_both[p1]
			p1 += 1
		else:
			ans += times_alice[p2] + times_bob[p3]
			p2 += 1
			p3 += 1
print(ans)


import sys
from collections import Counter as CO
input = sys.stdin.readline
from collections import defaultdict as dd
(n, k) = map(int, input().split())
arr = []
brr = []
both = []
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		both += [t]
	elif a == 1:
		arr += [t]
	elif b == 1:
		brr += [t]
ans = []
both.sort(reverse=True)
arr.sort(reverse=True)
brr.sort(reverse=True)
for i in range(k):
	if len(both) > 0 and min(len(arr), len(brr)) > 0:
		if both[-1] < arr[-1] + brr[-1]:
			ans += [both.pop()]
		else:
			ans += [arr.pop() + brr.pop()]
	elif len(both) == 0 and min(len(arr), len(brr)) > 0:
		ans += [arr.pop() + brr.pop()]
	elif len(both) > 0 and min(len(arr), len(brr)) == 0:
		ans += [both.pop()]
	else:
		break
if len(ans) < k:
	print(-1)
else:
	print(sum(ans))


from sys import stdin, stdout, setrecursionlimit
from collections import deque, defaultdict, Counter
from heapq import heappush, heappop
import math
rl = lambda : stdin.readline()
rll = lambda : stdin.readline().split()
rli = lambda : map(int, stdin.readline().split())
rlf = lambda : map(float, stdin.readline().split())
(INF, NINF) = (float('inf'), float('-inf'))

def main():
	(n, k) = rli()
	(both, alice, bob) = ([], [], [])
	for _ in range(n):
		(t, a, b) = rli()
		if a and b:
			both.append(t)
		elif a:
			alice.append(t)
		elif b:
			bob.append(t)
	both.sort(reverse=True)
	alice.sort(reverse=True)
	bob.sort(reverse=True)
	(read, time) = (0, 0)
	while read < k and (alice or bob or both):
		a = alice[-1] if alice else INF
		b = bob[-1] if bob else INF
		bo = both[-1] if both else INF
		if a + b == INF and bo == INF:
			break
		if a + b <= bo:
			time += a + b
			alice.pop()
			bob.pop()
		else:
			time += bo
			both.pop()
		read += 1
	print(time if read == k else -1)
	stdout.close()
main()


(n, k) = map(int, input().split())
abt = []
at = []
bt = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a & b:
		abt.append(t)
	elif a:
		at.append(t)
	elif b:
		bt.append(t)
at.sort()
bt.sort()
for i in range(min(len(at), len(bt))):
	abt.append(at[i] + bt[i])
if len(abt) < k:
	print(-1)
else:
	print(sum(sorted(abt)[:k]))


(n, k) = map(int, input().split())
z = []
x = []
y = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a & b:
		z.append(t)
	elif a:
		x.append(t)
	elif b:
		y.append(t)
x.sort()
y.sort()
for i in range(min(len(x), len(y))):
	z.append(x[i] + y[i])
print(-1 if len(z) < k else sum(sorted(z)[:k]))
num_inp = lambda : int(input())
arr_inp = lambda : list(map(int, input().split()))
sp_inp = lambda : map(int, input().split())
str_inp = lambda : input()


(n, kk) = map(int, input().split())
alice = []
bob = []
both = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
alice.sort()
bob.sort()
both.sort()
count = 0
l = min(len(alice), len(bob))
i = 0
j = 0
k = 0
ans = 0
if len(both) + len(bob) < kk or len(alice) + len(both) < kk:
	print(-1)
else:
	while j < l and count < kk:
		if k >= len(both) or alice[j] + bob[j] < both[k]:
			ans += alice[j] + bob[j]
			j += 1
			count += 1
		else:
			ans += both[k]
			k += 1
			count += 1
	print(ans + sum(both[k:k + kk - count]))


(n, k) = map(int, input().split())
t = []
a = []
b = []
n1 = 0
n2 = 0
n3 = 0
for _ in range(n):
	(x, y, z) = map(int, input().split())
	if y == 1 and z == 1:
		t.append(x)
		n1 += 1
	elif y == 1:
		a.append(x)
		n2 += 1
	elif z == 1:
		b.append(x)
		n3 += 1
t.sort()
a.sort()
b.sort()
nc = min(n2, n3)
c = [a[i] + b[i] for i in range(min(n2, n3))]
ans = 0
i = 0
j = 0
while i < n1 and j < nc and (k > 0):
	if t[i] <= c[j]:
		i += 1
		ans += t[i - 1]
	else:
		j += 1
		ans += c[j - 1]
	k -= 1
	if k == 0:
		break
while k > 0 and i < n1:
	i += 1
	ans += t[i - 1]
	k -= 1
while k > 0 and j < nc:
	j += 1
	ans += c[j - 1]
	k -= 1
if k > 0:
	print(-1)
else:
	print(ans)


(n, k) = [int(x) for x in input().split()]
(a, b, ab) = ([0], [0], [0])
for _ in range(n):
	(p, q, r) = [int(x) for x in input().split()]
	if q == 1:
		if r == 1:
			ab.append(p)
		else:
			a.append(p)
	elif r == 1:
		b.append(p)
if len(ab) - 1 + min(len(a) - 1, len(b) - 1) < k:
	print(-1)
	exit()
a.sort()
b.sort()
ab.sort()
sumo = 0
for i in range(len(a)):
	sumo += a[i]
	a[i] = sumo
sumo = 0
for i in range(len(b)):
	sumo += b[i]
	b[i] = sumo
sumo = 0
for i in range(len(ab)):
	sumo += ab[i]
	ab[i] = sumo
minans = int(10000000000.0)
for kp in range(max(0, k + 1 - min(len(a), len(b))), min(len(ab), k + 1)):
	minans = min(minans, a[k - kp] + b[k - kp] + ab[kp])
print(minans)


from sys import stdin
input = stdin.buffer.readline
(n, k) = map(int, input().split())
(a, b, c) = ([], [], [])
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x & y:
		c.append(t)
	elif x:
		a.append(t)
	elif y:
		b.append(t)
a.sort(reverse=True)
b.sort(reverse=True)
c.sort(reverse=True)
ans = 0
for i in range(k):
	if a and b and c:
		if c[-1] < a[-1] + b[-1]:
			ans += c.pop()
		else:
			ans += a.pop() + b.pop()
	elif c:
		ans += c.pop()
	elif a and b:
		ans += a.pop() + b.pop()
	else:
		exit(print(-1))
print(ans)


(n, k) = map(int, input().split())
a = []
b = []
both = []
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x == 1 and y == 1:
		both.append(t)
	elif x == 1:
		a.append(t)
	elif y == 1:
		b.append(t)
a.sort()
b.sort()
both.sort()
x = len(a)
if len(b) < len(a):
	x = len(b)
if x > k:
	x = k
min = 0
for i in range(0, x):
	min += a[i]
	min += b[i]
possible = True
if k - x > len(both):
	print(-1)
	possible = False
if possible == True:
	for j in range(0, k - x):
		min += both[j]
	if k == x:
		j = -1
	j += 1
	if x == 0:
		i = -1
	sum = min
	while True:
		if i == -1 or j == len(both):
			break
		sum += both[j]
		sum -= a[i]
		sum -= b[i]
		if sum < min:
			min = sum
		i -= 1
		j += 1
	print(min)


import sys
(n, k) = map(int, input().split())
bothlike = []
alike = []
blike = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		bothlike.append(t)
	if a == 1 and b == 0:
		alike.append(t)
	if a == 0 and b == 1:
		blike.append(t)
if len(alike) + len(bothlike) < k or len(blike) + len(bothlike) < k:
	print(-1)
	return
alike.sort()
blike.sort()
bothlike.sort()
asum = [0]
current = 0
for i in range(len(alike)):
	current += alike[i]
	asum.append(current)
bsum = [0]
current = 0
for i in range(len(blike)):
	current += blike[i]
	bsum.append(current)
bothcurrent = 0
ans = 10 ** 18
alen = len(alike)
blen = len(blike)
bothlen = len(bothlike)
for i in range(bothlen + 1):
	if i > 0:
		bothcurrent += bothlike[i - 1]
	if i > k:
		break
	if k - i > alen or k - i > blen:
		continue
	ans = min(ans, asum[k - i] + bsum[k - i] + bothcurrent)
print(ans)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
(n, k) = list(map(int, input().split()))
both = []
a = []
b = []
for _ in range(n):
	(t, ai, bi) = map(int, input().split())
	if ai == 1 and bi == 1:
		both.append(t)
	elif ai == 1:
		a.append(t)
	elif bi == 1:
		b.append(t)
both.sort()
a.sort()
b.sort()
found = True
for l in [both, a, b]:
	if len(l) < k:
		l += [10 ** 10] * (k - len(l))
if len(a) > k:
	a = a[:k]
if len(b) > k:
	b = b[:k]
if len(both) > k:
	both = both[:k]
out = 0
for i in range(k):
	out += min(a[i] + b[i], both[-i - 1])
if out >= 10 ** 10:
	print(-1)
else:
	print(out)


(n, k) = map(int, input().split())
both = []
alice = []
bob = []
none = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
	else:
		none.append(t)
flag = 0
both.sort()
alice.sort()
bob.sort()
if len(both) < k:
	if len(alice) + len(both) < k or len(bob) + len(both) < k:
		print(-1)
		flag = 1
bothpt = 0
bobpt = 0
alicept = 0
count = 0
if flag == 0:
	for i in range(k):
		if alicept >= len(alice) or bobpt >= len(bob):
			count += both[bothpt]
			bothpt += 1
			continue
		if bothpt < len(both) and both[bothpt] <= alice[alicept] + bob[bobpt]:
			count += both[bothpt]
			bothpt += 1
		else:
			count += alice[alicept] + bob[bobpt]
			alicept += 1
			bobpt += 1
	print(count)


import math

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def lcm(a, b):
	return a * b / gcd(a, b)

def bs(arr, l, r, x):
	while l <= r:
		mid = l + (r - l) // 2
		if arr[mid] == x:
			return arr[mid]
		elif arr[mid] < x:
			l = mid + 1
		else:
			r = mid - 1
	return -1

def swap(list, pos1, pos2):
	(list[pos1], list[pos2]) = (list[pos2], list[pos1])
	return list
t = 1
for _ in range(t):
	(n, k) = map(int, input().split())
	x = []
	c = 0
	ans = 0
	y01 = []
	y10 = []
	y11 = []
	for i in range(n):
		(tt, a, b) = map(int, input().split())
		if a == 1 and b == 1:
			y11.append(tt)
		elif a == 1 and b == 0:
			y10.append(tt)
		elif a == 0 and b == 1:
			y01.append(tt)
	y11.sort()
	y01.sort()
	y10.sort()
	f = 0
	i = 0
	j = 0
	while k:
		k -= 1
		if i < len(y11) and (j < len(y01) and j < len(y10)):
			if y11[i] < y01[j] + y10[j]:
				ans += y11[i]
				i += 1
			else:
				ans += y10[j] + y01[j]
				j += 1
		elif i < len(y11):
			ans += y11[i]
			i += 1
		elif j < len(y01) and j < len(y10):
			ans += y10[j] + y01[j]
			j += 1
		else:
			f = 1
	if f:
		print(-1)
		continue
	print(ans)


from sys import stdin, stdout
(n, k) = stdin.readline().strip().split(' ')
(n, k) = (int(n), int(k))
books = []
for i in range(n):
	(t, a, b) = stdin.readline().strip().split(' ')
	(t, a, b) = (int(t), int(a), int(b))
	books.append((t, a, b))
pairs_a = []
pairs_b = []
single = []
for i in books:
	if i[1] == 1 and i[2] == 1:
		single.append(i[0])
	elif i[1] or i[2] == 1:
		if i[1] == 1:
			pairs_a.append(i[0])
		else:
			pairs_b.append(i[0])
pairs_b = sorted(pairs_b)
pairs_a = sorted(pairs_a)
pairs = []
for i in range(min(len(pairs_a), len(pairs_b))):
	single.append(pairs_a[i] + pairs_b[i])
single = sorted(single)
if len(single) < k:
	stdout.write(str(-1) + '\n')
else:
	stdout.write(str(sum(single[:k])) + '\n')


import heapq
from sys import stdin
input = stdin.readline
INF = 2 * 10 ** 9 + 7
MAX = 10 ** 7 + 7
MOD = 10 ** 9 + 7
(n, M, k) = [int(x) for x in input().strip().split()]
(c, a, b, u) = ([], [], [], [])
for ni in range(n):
	(ti, ai, bi) = [int(x) for x in input().strip().split()]
	if ai == 1 and bi == 1:
		c.append((ti, ni + 1))
	elif ai == 1:
		a.append((ti, ni + 1))
	elif bi == 1:
		b.append((ti, ni + 1))
	else:
		u.append((ti, ni + 1))
c.sort(reverse=True)
a.sort(reverse=True)
b.sort(reverse=True)
u.sort(reverse=True)
alen = len(a)
blen = len(b)
clen = len(c)
ulen = len(u)
m = max(0, k - min(alen, blen), 2 * k - M)
ans = 0
alist = []
adlist = []
if m > clen:
	print('-1')
else:
	for mi in range(m):
		(cv, ci) = c.pop()
		ans += cv
		heapq.heappush(alist, (-cv, ci))
	ka = k - m
	kb = k - m
	M -= m
	while ka or kb:
		ca = c[-1][0] if c else INF
		da = 0
		(ap, bp) = (0, 0)
		if ka:
			da += a[-1][0] if a else INF
			ap = 1
		if kb:
			da += b[-1][0] if b else INF
			bp = 1
		if da <= ca and M >= 2:
			ans += da
			if ap:
				ka -= 1
				adlist.append(a[-1] if a else (INF, -1))
				if a:
					a.pop()
				M -= 1
			if bp:
				kb -= 1
				adlist.append(b[-1] if b else (INF, -1))
				if b:
					b.pop()
				M -= 1
		else:
			ans += ca
			heapq.heappush(alist, (-c[-1][0], c[-1][1]) if c else (INF, -1))
			if c:
				c.pop()
			if ap:
				ka -= 1
			if bp:
				kb -= 1
			M -= 1
	if M > len(a) + len(c) + len(b) + len(u) or ans >= INF:
		print('-1')
	else:
		heapq.heapify(c)
		while M > 0:
			if u and u[-1][0] <= min(c[0][0] if c else INF, a[-1][0] if a else INF, b[-1][0] if b else INF):
				(ut, dt) = (0, 0)
				ut += -alist[0][0] if alist else 0
				ut += u[-1][0]
				dt += a[-1][0] if a else INF
				dt += b[-1][0] if b else INF
				if ut < dt:
					upopped = u.pop()
					adlist.append(upopped)
					M -= 1
					ans += upopped[0]
				else:
					alpopped = heapq.heappop(alist) if alist else (-INF, -1)
					heapq.heappush(c, (-alpopped[0], alpopped[1]))
					ans += alpopped[0]
					bpopped = b.pop() if b else (INF, -1)
					apopped = a.pop() if a else (INF, -1)
					adlist.append(bpopped)
					adlist.append(apopped)
					ans += apopped[0]
					ans += bpopped[0]
					M -= 1
			else:
				ct = c[0][0] if c else INF
				(at, bt) = (a[-1][0] if a else INF, b[-1][0] if b else INF)
				abt = min(at, bt)
				if ct < abt:
					cpopped = heapq.heappop(c) if c else (INF, -1)
					heapq.heappush(alist, (-cpopped[0], cpopped[1]))
					ans += cpopped[0]
					M -= 1
				else:
					if at < bt:
						apopped = a.pop() if a else (INF, -1)
						adlist.append(apopped)
						ans += apopped[0]
					else:
						bpopped = b.pop() if b else (INF, -1)
						adlist.append(bpopped)
						ans += bpopped[0]
					M -= 1
			if ans >= INF:
				break
		print(ans if ans < INF else '-1')
		if ans < INF:
			for ai in adlist:
				print(ai[1], end=' ')
			for ai in alist:
				print(ai[1], end=' ')
			print('')


from sys import stdin
input = stdin.readline

def answer():
	if n3 + n1 < k or n3 + n2 < k:
		return -1
	(i, j) = (0, 0)
	ans = 0
	for take in range(k):
		if i >= n1 or i >= n2:
			ans += common[j]
			j += 1
		elif j >= n3:
			ans += a[i] + b[i]
			i += 1
		elif a[i] + b[i] > common[j]:
			ans += common[j]
			j += 1
		else:
			ans += a[i] + b[i]
			i += 1
	return ans
(n, k) = map(int, input().split())
(a, b, common) = ([], [], [])
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x and y:
		common.append(t)
	elif x == 1 and y == 0:
		a.append(t)
	elif x == 0 and y == 1:
		b.append(t)
common.sort()
a.sort()
b.sort()
(n1, n2, n3) = (len(a), len(b), len(common))
print(answer())


from typing import List, Tuple

def solve(n: int, k: int, tab: List[Tuple[int, int, int]]):
	(both, a_only, b_only) = ([], [], [])
	for (t, a, b) in tab:
		if a == 1 and b == 1:
			both.append(t)
		elif a == 1:
			a_only.append(t)
		elif b == 1:
			b_only.append(t)
	both.sort()
	a_only.sort()
	b_only.sort()
	idx_both = idx_a_only = idx_b_only = 0
	(len_both, len_a_only, len_b_only) = (len(both), len(a_only), len(b_only))
	times = []
	while len(times) < k and idx_both < len_both and (idx_a_only < len_a_only) and (idx_b_only < len_b_only):
		if both[idx_both] < a_only[idx_a_only] + b_only[idx_b_only]:
			times.append(both[idx_both])
			idx_both += 1
		else:
			times.append(a_only[idx_a_only] + b_only[idx_b_only])
			idx_a_only += 1
			idx_b_only += 1
	while len(times) < k and idx_both < len_both:
		times.append(both[idx_both])
		idx_both += 1
	while len(times) < k and idx_a_only < len_a_only and (idx_b_only < len_b_only):
		times.append(a_only[idx_a_only] + b_only[idx_b_only])
		idx_a_only += 1
		idx_b_only += 1
	return sum(times) if len(times) == k else -1
(n, k) = map(int, input().split())
tab = []
for _ in range(n):
	(t, a, b) = map(int, input().split())
	tab.append((t, a, b))
print(solve(n, k, tab))


(k, n) = [int(i) for i in input().split()]
a = []
b = []
both = []
for _ in range(k):
	(t, x, y) = [int(i) for i in input().split()]
	if x == 1 and y == 1:
		both.append(t)
	elif x == 1:
		a.append(t)
	elif y == 1:
		b.append(t)
a.sort()
b.sort()
both.sort()
if len(a) + len(both) < n or len(b) + len(both) < n:
	print(-1)
	quit()
bI = 0
aI = 0
bothI = 0
count = 0
t = 0
while count < n:
	count += 1
	if len(a) != aI and len(b) != bI and (len(both) != bothI):
		if a[aI] + b[bI] < both[bothI]:
			t += a[aI] + b[bI]
			aI += 1
			bI += 1
		else:
			t += both[bothI]
			bothI += 1
	elif len(a) != aI and len(b) != bI:
		t += a[aI] + b[bI]
		aI += 1
		bI += 1
	else:
		t += both[bothI]
		bothI += 1
print(t)


(n, k) = map(int, input().split(' '))
x = [40000]
y = [40000]
z = [40000]
c = d = 0
for i in range(n):
	(t, a, b) = map(int, input().split(' '))
	if a == 1 and b == 1:
		z.append(t)
		c += 1
		d += 1
	elif a == 1:
		x.append(t)
		c += 1
	elif b == 1:
		y.append(t)
		d += 1
if c < k or d < k:
	print(-1)
else:
	x.sort(reverse=True)
	y.sort(reverse=True)
	z.sort(reverse=True)
	c = d = ans = 0
	while c < k or d < k:
		if c < k and d < k:
			if x[len(x) - 1] + y[len(y) - 1] < z[len(z) - 1]:
				ans += x[len(x) - 1] + y[len(y) - 1]
				x.pop()
				y.pop()
			else:
				ans += z[len(z) - 1]
				z.pop()
			c += 1
			d += 1
		elif c < k:
			if x[len(x) - 1] < z[len(z) - 1]:
				ans += x[len(x) - 1]
				x.pop()
			else:
				ans += z[len(z) - 1]
				z.pop()
			c += 1
		else:
			if y[len(y) - 1] < z[len(z) - 1]:
				ans += y[len(y) - 1]
				y.pop()
			else:
				ans += z[len(z) - 1]
				z.pop()
			d += 1
	print(ans)


import sys
from collections import deque, defaultdict
input = sys.stdin.buffer.readline
(n, k) = map(int, input().split())
(al, bl, cc) = ([], [], [])
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a and (not b):
		al.append(t)
	elif not a and b:
		bl.append(t)
	elif a and b:
		cc.append(t)
al.sort()
bl.sort()
for i in range(min(len(al), len(bl))):
	cc.append(al[i] + bl[i])
cc.sort()
if len(cc) < k:
	print(-1)
else:
	print(sum(cc[0:k]))


from sys import stdin, stdout

def main():
	(n, k) = map(int, stdin.readline().split())
	alice = []
	bob = []
	both = []
	ans = 0
	for i in range(n):
		(t, a, b) = map(int, stdin.readline().split())
		ans += t
		if a == 1 and b == 1:
			both.append(t)
		elif a == 1:
			alice.append(t)
		elif b == 1:
			bob.append(t)
		else:
			pass
	alice.sort()
	bob.sort()
	both.sort()
	for i in range(1, len(alice)):
		alice[i] += alice[i - 1]
	for i in range(1, len(bob)):
		bob[i] += bob[i - 1]
	for i in range(1, len(both)):
		both[i] += both[i - 1]
	(la, lbb, lbo) = (len(alice), len(bob), len(both))
	if la + lbo < k or lbb + lbo < k:
		ans = -1
	else:
		for i in range(lbo):
			rest = k - i - 1
			if rest > 0:
				if la >= rest and lbb >= rest:
					ans = min(ans, both[i] + alice[rest - 1] + bob[rest - 1])
			else:
				ans = min(ans, both[i])
		if la >= k and lbb >= k:
			ans = min(ans, alice[k - 1] + bob[k - 1])
	stdout.write(str(ans))
	stdout.write('\n')
	return
main()


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
(n, k) = sp()
mat = []
(a, b, both) = ([], [], [])
for i in range(n):
	(ti, ai, bi) = sp()
	if ai and bi:
		both.append(ti)
		continue
	if ai:
		a.append(ti)
	if bi:
		b.append(ti)
if len(a) + len(both) < k or len(b) + len(both) < k:
	out(-1)
	exit()
a.sort(reverse=True)
b.sort(reverse=True)
both.sort(reverse=True)
answer = 0
for i in range(k):
	t1 = inf if not a else a[-1]
	t2 = inf if not b else b[-1]
	t3 = inf if not both else both[-1]
	if t3 < t1 + t2:
		answer += t3
		both.pop()
	else:
		answer += t1 + t2
		a.pop()
		b.pop()
out(answer)


from sys import stdin, stdout
import math, sys
from itertools import permutations, combinations
from collections import defaultdict, deque, OrderedDict
from os import path
import bisect as bi
import heapq

def yes():
	print('YES')

def no():
	print('NO')
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

	def I():
		return int(input())

	def In():
		return map(int, input().split())
else:

	def I():
		return int(stdin.readline())

	def In():
		return map(int, stdin.readline().split())

def main():
	try:
		(n, k) = In()
		(l1, l2, l3) = ([], [], [])
		for x in range(n):
			(t, a, b) = In()
			if a == 1 and b == 1:
				l1.append(t)
			elif a == 0 and b == 1:
				l3.append(t)
			elif a == 1 and b == 0:
				l2.append(t)
			else:
				continue
		l2.sort()
		l3.sort()
		l4 = []
		if len(l2) < len(l3):
			for x in range(len(l2)):
				l4.append(l2[x] + l3[x])
		elif len(l2) >= len(l3) and len(l2) != 0:
			for x in range(len(l3)):
				l4.append(l2[x] + l3[x])
		l1 += l4
		if k > len(l1):
			print(-1)
		else:
			ans = 0
			l1.sort()
			for x in range(k):
				ans += l1[x]
			print(ans)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(1):
	main()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	(n, k) = RL()
	na = 0
	nb = 0
	ab = 0
	(ar, br, abr) = ([], [], [])
	for _ in range(n):
		(t, a, b) = RL()
		if a and (not b):
			na += 1
			ar.append(t)
		if b and (not a):
			nb += 1
			br.append(t)
		if a == 1 and b == 1:
			ab += 1
			abr.append(t)
	if na + ab < k or nb + ab < k:
		print(-1)
	else:
		ar.sort()
		br.sort()
		for (a, b) in zip(ar, br):
			abr.append(a + b)
		abr.sort()
		print(sum(abr[:k]))
main()


from collections import Counter, defaultdict
BS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def to_base(s, b):
	res = ''
	while s:
		res += BS[s % b]
		s //= b
	return res[::-1] or '0'
alpha = 'abcdefghijklmnopqrstuvwxyz'
from math import floor, ceil, pi
import sys
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087, 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791, 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133, 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833, 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207, 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919]
import timeit

def primef(n, plst=[]):
	if n == 1:
		return plst
	else:
		for m in primes:
			if n % m == 0:
				return primef(n // m, plst + [m])
		return primef(1, plst + [n])

def lmii():
	return list(map(int, input().split()))

def ii():
	return int(input())

def countOverlapping(string, sub):
	count = start = 0
	while True:
		start = string.find(sub, start) + 1
		if start > 0:
			count += 1
		else:
			return count
(n, k) = lmii()
gotA = []
gotB = []
got = []
nums = [list(map(int, sys.stdin.readline().split())) for i in range(n)]
nums.sort()
for i in range(n):
	(a, b, c) = nums[i]
	if b + c == 2:
		got.append(a)
	elif b + c != 0:
		if b == 0:
			if gotB:
				(aa, bb, cc) = gotB.pop(0)
				got.append(aa + a)
			else:
				gotA.append((a, b, c))
		elif gotA:
			(aa, bb, cc) = gotA.pop(0)
			got.append(aa + a)
		else:
			gotB.append((a, b, c))
got.sort()
if len(got) < k:
	print(-1)
else:
	print(sum(got[:k]))


import sys

def answer(n, k, t, a, b):
	t_both = []
	t_a = []
	t_b = []
	for i in range(n):
		if a[i] == 1 and b[i] == 1:
			t_both.append(t[i])
		elif a[i] == 1:
			t_a.append(t[i])
		elif b[i] == 1:
			t_b.append(t[i])
	if k > len(t_both) + min(len(t_a), len(t_b)):
		return -1
	t_both.sort()
	t_a.sort()
	t_b.sort()
	both_ctr = 0
	ab_ctr = 0
	ans = 0
	for i in range(k):
		best_t_both = 10 ** 5
		best_ind = 10 ** 5
		if both_ctr < len(t_both):
			best_t_both = t_both[both_ctr]
		if ab_ctr < min(len(t_a), len(t_b)):
			best_ind = t_a[ab_ctr] + t_b[ab_ctr]
		if best_t_both < best_ind:
			ans += best_t_both
			both_ctr += 1
		else:
			ans += best_ind
			ab_ctr += 1
	return ans

def main():
	(n, k) = map(int, sys.stdin.readline().split())
	t = [0 for _ in range(n)]
	a = [0 for _ in range(n)]
	b = [0 for _ in range(n)]
	for i in range(n):
		(t[i], a[i], b[i]) = map(int, sys.stdin.readline().split())
	print(answer(n, k, t, a, b))
	return
main()


(n, k) = map(int, input().split())
group = [[], [], [], []]
for i in range(n):
	(t, a, b) = map(int, input().split())
	group[a * 2 + b].append(t)
pref_sum = [[0], [0], [0], [0]]
for (g, ps) in zip(group, pref_sum):
	g.sort()
	for i in g:
		ps.append(ps[-1] + i)
ans = 10 ** 18
for i in range(min(k, len(group[3])) + 1):
	rest = k - i
	if rest > len(group[2]) or rest > len(group[1]):
		continue
	ans = min(ans, pref_sum[3][i] + pref_sum[1][rest] + pref_sum[2][rest])
if ans < 10 ** 18:
	print(ans)
else:
	print(-1)


(n, k) = [int(i) for i in input().split()]
a1 = []
a2 = []
a3 = []
A1 = False
A2 = False
A3 = False
amount = 0
summ = 0
for i in range(n):
	(t, a, b) = [int(z) for z in input().split()]
	if a == 1 and b == 1:
		a1.append(t)
		A1 = True
	elif a == 1:
		a2.append(t)
		A2 = True
	elif b == 1:
		a3.append(t)
		A3 = True
a1 = sorted(a1)
a2 = sorted(a2)
a3 = sorted(a3)
if len(a1) + min(len(a2), len(a3)) < k:
	print(-1)
else:
	(x, y) = (0, 0)
	len1 = len(a1)
	len2 = len(a2)
	len3 = len(a3)
	while amount < k:
		if x == len2 or x == len3:
			summ += sum(a1[y:y + k - amount])
			break
		if y == len1:
			summ += sum(a2[x:x + k - amount] + a3[x:x + k - amount])
			break
		if a3[x] + a2[x] < a1[y]:
			summ += a3[x] + a2[x]
			x += 1
			amount += 1
		else:
			summ += a1[y]
			y += 1
			amount += 1
	print(summ)


from collections import deque
(n, k) = list(map(int, input().split()))
both_ls = []
a_ls = []
b_ls = []
for i in range(n):
	(t, a, b) = list(map(int, input().split()))
	if a == 1 and b == 0:
		a_ls.append(t)
	elif a == 0 and b == 1:
		b_ls.append(t)
	elif a == 1 and b == 1:
		both_ls.append(t)
a_ls = sorted(a_ls)
b_ls = sorted(b_ls)
both_ls = sorted(both_ls)
a_ls = deque(a_ls)
b_ls = deque(b_ls)
both_ls = deque(both_ls)
res = 0
broke = False
for i in range(k):
	if len(both_ls) > 0 and len(a_ls) > 0 and (len(b_ls) > 0):
		if both_ls[0] >= a_ls[0] + b_ls[0]:
			res += a_ls.popleft()
			res += b_ls.popleft()
		else:
			res += both_ls.popleft()
	elif len(both_ls) > 0:
		res += both_ls.popleft()
	elif len(a_ls) > 0 and len(b_ls) > 0:
		res += a_ls.popleft()
		res += b_ls.popleft()
	else:
		print(-1)
		broke = True
		break
if not broke:
	print(res)


import os
import heapq
import sys
import math
import operator
from collections import defaultdict
from copy import copy
from io import BytesIO, IOBase

def inpt():
	return [int(k) for k in input().split()]

def main():
	(n, k) = map(int, input().split())
	a = []
	b = []
	both = []
	for i in range(n):
		(t, aa, bb) = map(int, input().split())
		if aa != 0 and aa == bb:
			both.append(t)
		elif aa:
			a.append(t)
		elif bb:
			b.append(t)
	a.sort()
	b.sort()
	i = 0
	while i != min(len(a), len(b)):
		both.append(a[i] + b[i])
		i += 1
	both.sort()
	ans = 0
	for i in both:
		if k == 0:
			break
		ans += i
		k -= 1
	if k > 0:
		print(-1)
	else:
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


(n, k) = list(map(int, input().split()))
ar1 = []
ar2 = []
ar3 = []
for i in range(n):
	ar = list(map(int, input().split()))
	if ar[1] == 1 and ar[2] == 0:
		ar1.append(ar)
	elif ar[1] == 0 and ar[2] == 1:
		ar2.append(ar)
	elif ar[1] == ar[2] == 1:
		ar3.append(ar)
ar1.sort()
ar2.sort()
ar3.sort()
(i, j, h) = (0, 0, 0)
(num1, num2) = (k, k)
ans = 0
while (i < len(ar1) and j < len(ar2) or h < len(ar3)) and num1 > 0 and (num2 > 0):
	if h >= len(ar3):
		ans += ar1[i][0] + ar2[j][0]
		i += 1
		j += 1
	elif i >= len(ar1) or j >= len(ar2):
		ans += ar3[h][0]
		h += 1
	elif ar1[i][0] + ar2[j][0] > ar3[h][0]:
		ans += ar3[h][0]
		h += 1
	else:
		ans += ar1[i][0] + ar2[j][0]
		i += 1
		j += 1
	num1 -= 1
	num2 -= 1
if num1 > 0 or num2 > 0:
	print(-1)
else:
	print(ans)


from sys import stdin
input = stdin.readline

def answer():
	if n3 + n1 < k or n3 + n2 < k:
		return -1
	for i in range(1, n1 + 1):
		a[i] += a[i - 1]
	for i in range(1, n2 + 1):
		b[i] += b[i - 1]
	start = max(max(0, k - n1), max(0, k - n2))
	s = 0
	for i in range(start):
		s += common[i]
	ans = 10000000000.0
	for i in range(start, min(k, n3) + 1):
		ans = min(ans, s + a[k - i] + b[k - i])
		s += common[i]
	return ans
(n, k) = map(int, input().split())
(a, b, common) = ([0], [0], [])
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x and y:
		common.append(t)
	elif x == 1 and y == 0:
		a.append(t)
	elif x == 0 and y == 1:
		b.append(t)
common.sort()
a.sort()
b.sort()
common.append(0)
(n1, n2, n3) = (len(a) - 1, len(b) - 1, len(common) - 1)
print(answer())


import sys
import random
from math import *

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def finput():
	return float(input())

def tinput():
	return input().split()

def linput():
	return list(input())

def rinput():
	return map(int, tinput())

def fiinput():
	return map(float, tinput())

def rlinput():
	return list(map(int, input().split()))

def trinput():
	return tuple(rinput())

def srlinput():
	return sorted(list(map(int, input().split())))

def NOYES(fl):
	if fl:
		print('NO')
	else:
		print('YES')

def YESNO(fl):
	if fl:
		print('YES')
	else:
		print('NO')

def main():
	(n, k) = rinput()
	q = []
	for i in range(n):
		q.append(rlinput())
	q.sort()
	(w, e, r, fak, pr, pe, pw) = ([], [], [], [], [0], [0], [0])
	(res1, res2) = (0, 0)
	for i in range(n):
		(res1, res2) = (res1 + q[i][1], res2 + q[i][2])
		if q[i][1] and q[i][2]:
			w.append(q[i][0])
			pw.append(w[-1] + pw[-1])
		elif q[i][1]:
			e.append(q[i][0])
			pe.append(e[-1] + pe[-1])
		elif q[i][2]:
			r.append(q[i][0])
			pr.append(r[-1] + pr[-1])
		else:
			fak.append(q[i])
	if min(res1, res2) < k:
		print(-1)
	else:
		res = 5000000000.0
		for i in range(1 + min(k, len(w))):
			if k - i <= min(len(r), len(e)):
				res = min(res, pw[i] + pr[k - i] + pe[k - i])
		print(res)
for inytd in range(1):
	main()


(n, k) = map(int, input().split())
x = []
y = []
z = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a and b:
		x.append(t)
	elif a == 1:
		y.append(t)
	elif b == 1:
		z.append(t)
y.sort()
z.sort()
for (p, q) in zip(y, z):
	x.append(p + q)
x.sort()
if len(x) < k:
	print(-1)
else:
	print(sum(x[:k]))


(n, k) = map(int, input().split())
(bot, ali, bob) = ([], [], [])
(alicetime, bobtime, count) = (0, 0, 0)
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		bot.append(t)
	elif a == 1 and b == 0:
		ali.append(t)
	elif a == 0 and b == 1:
		bob.append(t)
bot.sort(reverse=True)
ali.sort(reverse=True)
bob.sort(reverse=True)
while len(bot) > 0 and len(ali) > 0 and (len(bob) > 0) and (alicetime < k) and (bobtime < k):
	if bot[-1] <= ali[-1] + bob[-1]:
		x = bot.pop()
		count += x
		alicetime += 1
		bobtime += 1
	else:
		y = ali.pop()
		z = bob.pop()
		count += y + z
		alicetime += 1
		bobtime += 1
if len(bot) == 0 and len(ali) > 0 and (len(bob) > 0) and (alicetime < k) and (bobtime < k):
	while len(ali) > 0 and len(bob) > 0 and (alicetime < k) and (bobtime < k):
		y = ali.pop()
		z = bob.pop()
		count += y + z
		alicetime += 1
		bobtime += 1
elif len(bot) > 0 and (len(ali) == 0 or len(bob) == 0) and (alicetime < k) and (bobtime < k):
	while len(bot) > 0 and alicetime < k and (bobtime < k):
		x = bot.pop()
		count += x
		alicetime += 1
		bobtime += 1
if alicetime != k or bobtime != k:
	print(-1)
else:
	print(count)


from collections import Counter
from math import log2
(n, m) = map(int, input().split())
a = []
b = []
c = []
for i in range(n):
	(t, u, v) = map(int, input().split())
	if u == 0 and v == 0:
		continue
	elif u == 1 and v == 1:
		c.append(t)
	elif u == 1:
		a.append(t)
	else:
		b.append(t)
a.sort()
b.sort()
for i in range(min(len(a), len(b))):
	c.append(a[i] + b[i])
if len(c) < m:
	print(-1)
else:
	print(sum(sorted(c)[:m]))


from heapq import *
l = []
(n, k) = map(int, input().split())
(a, b, c) = ([], [], [])
for i in range(n):
	l.append(list(map(int, input().split())))
l.sort()
for i in range(n):
	(la, lb) = (len(a) + len(c), len(b) + len(c))
	if (l[i][1] == 1 or l[i][2] == 1) and (la < k or lb < k):
		if l[i][1] == 1 and l[i][2] == 0 and (la < k):
			heappush(a, -l[i][0])
		elif l[i][1] == 0 and l[i][2] == 1 and (lb < k):
			heappush(b, -l[i][0])
		elif l[i][1] == 1 and l[i][2] == 1:
			heappush(c, -l[i][0])
	elif (l[i][1] == 1 and l[i][2] == 1) and (la == k and lb == k):
		(ra, rb) = (0, 0)
		if len(a) > 0:
			ra = -a[0]
		if len(b) > 0:
			rb = -b[0]
		if ra + rb > l[i][0]:
			heappush(c, -l[i][0])
	if len(a) + len(c) > k:
		heappop(a)
	if len(b) + len(c) > k:
		heappop(b)
if len(a) + len(c) < k or len(b) + len(c) < k:
	print(-1)
else:
	print(-(sum(a) + sum(b) + sum(c)))


from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush, heappop
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
M = mod = 998244353

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split()]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
(n, k) = li()
alice = []
bob = []
both = []
for i in range(n):
	(a, b, c) = li()
	if b and c:
		both.append(a)
	elif b:
		alice.append(a)
	elif c:
		bob.append(a)
alice.sort()
bob.sort()
for i in range(min(len(alice), len(bob))):
	both.append(alice[i] + bob[i])
both.sort()
if len(both) < k:
	print(-1)
	exit()
else:
	print(sum(both[:k]))


t = 1
for _ in range(t):
	(n, k) = map(int, input().split())
	arr = []
	for i in range(n):
		(a, b, c) = map(int, input().split())
		arr.append((a, b, c))
	arr = sorted(arr, key=lambda x: x[0])
	ans = 0
	x = y = k
	counter = 0
	temp1 = []
	temp2 = []
	while counter < n:
		if x <= 0 and y <= 0:
			break
		if arr[counter][1] == 0 and arr[counter][2] == 0:
			counter += 1
			continue
		ans += arr[counter][0]
		x -= arr[counter][1]
		y -= arr[counter][2]
		if arr[counter][1] and (not arr[counter][2]):
			temp1.append(arr[counter][0])
		elif not arr[counter][1] and arr[counter][2]:
			temp2.append(arr[counter][0])
		counter += 1
	x_d = min(len(temp1), len(temp2))
	ans -= sum(temp1) + sum(temp2)
	temp1 = temp1[0:x_d]
	temp2 = temp2[0:x_d]
	ans += sum(temp1) + sum(temp2)
	if len(temp1) > 0 and len(temp2) > 0:
		temp1 = sorted(temp1)
		temp2 = sorted(temp2)
		for i in range(counter, n):
			if arr[i][1] == 1 and arr[i][2] == 1:
				if arr[i][0] < temp1[-1] + temp2[-1]:
					ans += arr[i][0] - (temp1[-1] + temp2[-1])
					temp1.pop()
					temp2.pop()
					if not (len(temp1) and len(temp2)):
						break
	if x > 0 or y > 0:
		print(-1)
	else:
		print(ans)


from math import *
from copy import *
from string import *
from random import *
from sys import stdin, stdout
from sys import maxsize
from operator import *
from itertools import *
from collections import Counter
import math
import math
import time
from queue import Queue

def seive(n):
	l = [True]
	l = l * (n + 1)
	for i in range(2, int(sqrt(n)) + 1):
		if l[i] == True:
			val = i * i
			while val < len(l):
				l[val] = False
				val += i
	prime = []
	for i in range(2, len(l)):
		if l[i] == True:
			prime.append(i)
	return prime

def dp(l, i, n, val, ans):
	if i >= n or val < 0:
		return 1000000
	elif val == 0:
		return 0
	else:
		if ans[i] == 1000000:
			ans[i] = min(min(1 + dp(l, i + 1, n, val - l[i], ans), 1 + dp(l, i, n, val - l[i], ans)), dp(l, i + 1, n, val, ans))
		return ans[i]
from queue import Queue

def factors(n):
	l = []
	for i in range(1, int(sqrt(n)) + 1):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
	return l

def check1(s, v, x):
	while True:
		if v not in s:
			return v
		else:
			v -= 1

def check2(s, v, x):
	while True:
		if v not in s:
			return v
		else:
			v += 1

def up(n):
	j = n - 1
	while j > 0:
		if n % j == 0:
			break
		j -= 1
	return j
(n, k) = map(int, input().split(' '))
(alice, bob, both) = ([], [], [])
for i in range(n):
	(t, a, b) = map(int, input().split(' '))
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
bob.sort()
alice.sort()
both.sort()
if len(alice) == 0 or len(bob) == 0:
	if len(both) < k:
		print(-1)
	else:
		print(sum(both[0:k]))
else:
	i1 = 0
	i2 = 0
	i3 = 0
	c1 = 0
	c2 = 0
	ans = 0
	while i1 < len(alice) and i2 < len(bob) and (i3 < len(both)) and (c1 < k) and (c2 < k):
		if both[i3] <= alice[i1] + bob[i2]:
			c1 += 1
			c2 += 1
			ans += both[i3]
			i3 += 1
		else:
			c1 += 1
			c2 += 1
			ans += alice[i1]
			ans += bob[i2]
			i1 += 1
			i2 += 1
	if c1 == k and c2 == k:
		print(ans)
	elif i1 == len(alice) or i2 == len(bob):
		while i3 < len(both) and c1 < k and (c2 < k):
			ans += both[i3]
			c1 += 1
			c2 += 1
			i3 += 1
		if c1 != k:
			print(-1)
		else:
			print(ans)
	else:
		while i1 < len(alice) and c1 < k:
			ans += alice[i1]
			i1 += 1
			c1 += 1
		while i2 < len(bob) and c2 < k:
			ans += bob[i2]
			i2 += 1
			c2 += 1
		if c1 != k or c2 != k:
			print(-1)
		else:
			print(ans)


import sys
import math
import heapq
import collections
from collections import OrderedDict

def inputnum():
	return int(input())

def inputnums():
	return map(int, input().split())

def inputlist():
	return list(map(int, input().split()))

def inputstring():
	return [x for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
(n, k) = inputnums()
mins = [[[] for i in range(2)] for j in range(2)]
for i in range(n):
	(t, a, b) = inputnums()
	mins[a][b].append(t)
mins[1][0].sort()
mins[0][1].sort()
x = len(mins[1][0])
y = len(mins[0][1])
for i in range(min(x, y)):
	mins[1][1].append(mins[1][0][i] + mins[0][1][i])
mins[1][1].sort()
ans = 0
if len(mins[1][1]) < k:
	ans = -1
if ans != -1:
	for i in range(k):
		ans += mins[1][1][i]
print(ans)


(n, k) = map(int, input().split())
x = []
y = []
z = []
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		x.append(t)
	elif a == 1 and b == 0:
		y.append(t)
	elif a == 0 and b == 1:
		z.append(t)
x.sort()
y.sort()
z.sort()
kk = []
p = min(len(y), len(z))
for i in range(p):
	kk.append(y[i] + z[i])
if len(kk) + len(x) < k:
	print(-1)
else:
	i = 0
	j = 0
	c = []
	while True:
		if i == len(kk):
			c.extend(x[j:])
			break
		if j == len(x):
			c.extend(kk[i:])
			break
		if kk[i] > x[j]:
			c.append(x[j])
			j += 1
		elif kk[i] == x[j]:
			c.append(x[j])
			c.append(x[j])
			i += 1
			j += 1
		else:
			c.append(kk[i])
			i += 1
	print(sum(c[:k]))


(n, k) = map(int, input().split())
(a, b, ab) = ([], [], [])
for _ in range(n):
	(t, x, y) = map(int, input().split())
	if x == 1 and y == 1:
		ab.append(t)
	elif x == 1 and y == 0:
		a.append(t)
	elif x == 0 and y == 1:
		b.append(t)
if len(ab) + min(len(a), len(b)) < k:
	print(-1)
else:
	(cost, ind, tog) = (0, 0, 0)
	a.sort()
	b.sort()
	ab.sort()
	for i in range(k):
		if tog == len(ab):
			cost += sum(a[ind:ind + (k - i)]) + sum(b[ind:ind + (k - i)])
			break
		elif ind == min(len(a), len(b)):
			cost += sum(ab[tog:tog + (k - i)])
			break
		elif a[ind] + b[ind] < ab[tog]:
			cost += a[ind] + b[ind]
			ind += 1
		else:
			cost += ab[tog]
			tog += 1
	print(cost)


(n, k) = map(int, input().split())
alice = list()
bob = list()
common = list()
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		common.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
if len(common) + len(alice) < k:
	ans = -1
elif len(common) + len(bob) < k:
	ans = -1
else:
	common.sort()
	alice.sort()
	bob.sort()
	commonP = [0] * len(common)
	aliceP = [0] * len(alice)
	bobP = [0] * len(bob)
	if len(common) > 0:
		commonP[0] = common[0]
		for i in range(1, len(commonP)):
			commonP[i] = commonP[i - 1] + common[i]
	if len(alice) > 0:
		aliceP[0] = alice[0]
		for i in range(1, len(alice)):
			aliceP[i] = aliceP[i - 1] + alice[i]
	if len(bob) > 0:
		bobP[0] = bob[0]
		for i in range(1, len(bob)):
			bobP[i] = bobP[i - 1] + bob[i]
	if len(common) == 0:
		ans = aliceP[k - 1] + bobP[k - 1]
	else:
		ans = None
		for i in range(0, len(common) + 1):
			if i > k:
				break
			if i == k:
				choice = commonP[k - 1]
			else:
				if len(alice) < k - i or len(bob) < k - i:
					continue
				if i == 0:
					choice = 0
				else:
					choice = commonP[i - 1]
				try:
					choice += aliceP[k - i - 1]
				except:
					pass
				try:
					choice += bobP[k - i - 1]
				except:
					pass
			if ans == 0:
				continue
			if ans is None:
				ans = choice
			else:
				ans = min(ans, choice)
print(ans)


(n, m, k) = map(int, input().split())
ab = []
a = []
b = []
other = []
l = [list(map(int, input().split())) for i in range(n)]
for i in range(n):
	(t, c, d) = l[i]
	if c and d == 0:
		a.append([t, i + 1])
	elif d and c == 0:
		b.append([t, i + 1])
	elif c * d:
		ab.append([t, i + 1])
	else:
		other.append([t, i + 1])
a.sort()
b.sort()
ab.sort()
other.sort()
la = len(a)
lb = len(b)
lab = len(ab)
lo = len(other)
a.append([float('INF'), -1])
b.append([float('INF'), -1])
ab.append([float('INF'), -1])
other.append([float('INF'), -1])
if la < lb:
	(la, lb) = (lb, la)
	(a, b) = (b, a)
ans = float('INF')
count = 0
ia = 0
ib = 0
iab = 0
io = 0
ana = 0
anb = 0
anab = 0
ano = 0
for i in range(lab + 1):
	if k - i > lb:
		continue
	if 2 * k - i > m:
		continue
	if i + la + lb + lo < m:
		continue
	if ia > 0:
		ia -= 1
		count -= a[ia][0]
	if ib > 0:
		ib -= 1
		count -= b[ib][0]
	if io > 0:
		io -= 1
		count -= other[io][0]
	while ia < la and ia < k - i:
		count += a[ia][0]
		ia += 1
	while ib < lb and ib < k - i:
		count += b[ib][0]
		ib += 1
	while iab < lab and iab < i:
		count += ab[iab][0]
		iab += 1
	while ia + ib + iab + io < m:
		na = a[ia][0]
		nb = b[ib][0]
		no = other[io][0]
		mi = min(na, nb, no)
		if mi == na:
			count += na
			ia += 1
		elif mi == nb:
			count += nb
			ib += 1
		else:
			count += no
			io += 1
	if count < ans:
		ans = count
		ana = ia
		anb = ib
		anab = iab
		ano = io
if ans == float('INF'):
	print(-1)
else:
	print(ans)
	l = []
	for i in range(ana):
		l.append(a[i][1])
	for i in range(anb):
		l.append(b[i][1])
	for i in range(anab):
		l.append(ab[i][1])
	for i in range(ano):
		l.append(other[i][1])
	print(*l)


def read_ints():
	line = input()
	return [int(e) for e in line.strip().split(' ')]
(n, k) = read_ints()
a = []
b = []
t = []
for _ in range(n):
	(it, ia, ib) = read_ints()
	if ia == 1 and ib == 1:
		t.append(it)
	elif ia == 1:
		a.append(it)
	elif ib == 1:
		b.append(it)
a.sort()
b.sort()
for i in range(min(len(a), len(b))):
	t.append(a[i] + b[i])
t.sort()
print(-1 if len(t) < k else sum(t[:k]))


[N, K] = list(map(int, input().split()))
L = [[[] for i in range(2)] for j in range(2)]
for i in range(N):
	[t, a, b] = list(map(int, input().split()))
	L[a][b].append(t)
INF = int(1000000000000.0)
for i in range(2):
	for j in range(2):
		L[i][j].sort()
		for k in range(K - len(L[i][j])):
			L[i][j].append(INF)
ans = INF
now = 0
for i in range(K):
	now += L[1][1][i]
ans = min(ans, now)
for i in range(K):
	now -= L[1][1][K - i - 1]
	now += L[1][0][i]
	now += L[0][1][i]
	ans = min(ans, now)
if ans >= INF:
	ans = -1
print(ans)


q = 1
for Q in range(q):
	(n, k) = map(int, input().split())
	c01 = []
	c10 = []
	c11 = []
	for i in range(n):
		(t, a, b) = map(int, input().split())
		if a == 1 and b == 0:
			c10.append(t)
		if a == 0 and b == 1:
			c01.append(t)
		if a == 1 and b == 1:
			c11.append(t)
	c01.sort()
	c10.sort()
	c11.sort()
	if len(c10) + len(c11) < k or len(c01) + len(c11) < k:
		print(-1)
		continue
	sz = min(len(c01), len(c10))
	res = []
	for i in range(sz):
		res.append(c01[i] + c10[i])
	for i in c11:
		res.append(i)
	res.sort()
	ans = 0
	for i in range(k):
		ans += res[i]
	print(ans)


import os
import operator
from collections import defaultdict
import sys
from io import BytesIO, IOBase
import bisect

def main():
	(n, el) = map(int, input().split())
	oo = []
	zo = []
	oz = []
	for i in range(n):
		(t, a, b) = map(int, input().split())
		if a == b == 1:
			oo.append(t)
		elif a == 1 and b == 0:
			oz.append(t)
		elif a == 0 and b == 1:
			zo.append(t)
	oo.sort()
	zo.sort()
	oz.sort()
	alice = 0
	bob = 0
	i = 0
	j = 0
	k = 0
	ans = 0
	while True:
		if alice >= el and bob >= el:
			break
		if i < len(oo) and j < len(oz) and (k < len(zo)):
			if oo[i] < oz[j] + zo[k]:
				ans += oo[i]
				alice += 1
				bob += 1
				i += 1
			else:
				ans += oz[j] + zo[k]
				alice += 1
				bob += 1
				j += 1
				k += 1
		elif i < len(oo):
			ans += oo[i]
			alice += 1
			bob += 1
			i += 1
		elif j < len(oz) and k < len(zo):
			ans += oz[j] + zo[k]
			alice += 1
			bob += 1
			j += 1
			k += 1
		else:
			break
	if alice >= el and bob >= el:
		print(ans)
	else:
		print(-1)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


(n, k) = list(map(int, input().split()))
(ca, cb) = (0, 0)
(x, y, z) = ([], [], [])
for i in range(n):
	(t, a, b) = list(map(int, input().split()))
	ca += a
	cb += b
	if a == 1 and b == 0:
		x.append(t)
	elif a == 0 and b == 1:
		y.append(t)
	elif a == 1 and b == 1:
		z.append(t)
x.sort()
y.sort()
z.sort()
if ca < k or cb < k:
	print('-1')
else:
	total = 0
	arr = []
	for i in range(min(len(z), k)):
		total += z[i]
		arr.append(z[i])
	if len(z) < k:
		for i in range(len(z), k):
			total += x[0] + y[0]
			del x[0]
			del y[0]
	while len(x) > 0 and len(y) > 0 and (len(arr) > 0) and (x[0] + y[0] < arr[-1]):
		total += x[0] + y[0] - arr[-1]
		del arr[-1]
		del x[0]
		del y[0]
	print(total)


import sys

def fun(x):
	return x[0]
(n, k) = list(map(int, sys.stdin.readline().strip().split()))
xx = []
a = []
b = []
c = []
for i in range(n):
	x = list(map(int, sys.stdin.readline().strip().split()))
	if x[1] == x[2] == 1:
		a.append(x[0])
	elif x[1] == 1:
		b.append(x[0])
	elif x[2] == 1:
		c.append(x[0])
b.sort()
c.sort()
for i in range(min(len(b), len(c))):
	a.append(b[i] + c[i])
a.sort()
if len(a) < k:
	print(-1)
else:
	print(sum(a[:k]))


t = 1

def primes(n):
	count = 0
	rl = 0
	while n % 2 == 0:
		n = n // 2
		count += 1
	while n % 3 == 0:
		n = n // 3
		rl += 1
	if n != 1 or count > rl:
		return -1
	else:
		return [rl, count]
from math import *
for xy in range(t):
	(n, k) = [int(x) for x in input().split()]
	tq = {}
	sets = set()
	ar = []
	ac = []
	bb = []
	for i in range(n):
		(t, a, b) = [int(x) for x in input().split()]
		if a == 1 and b == 1:
			bb.append(t)
		elif a == 1:
			ar.append(t)
		elif b == 1:
			ac.append(t)
	ar = sorted(ar)
	ac = sorted(ac)
	bb = sorted(bb)
	i = 0
	j = 0
	count = 0
	lp = 0
	rq = True
	while lp < k:
		if i < len(ar) and i < len(ac) and (j < len(bb) and ac[i] + ar[i] <= bb[j] or j >= len(bb)):
			count += ar[i] + ac[i]
			i += 1
			lp += 1
		elif j < len(bb):
			count += bb[j]
			j += 1
			lp += 1
		else:
			rq = False
			break
	if rq:
		print(count)
	else:
		print(-1)


def answer():
	if n3 + n1 < k:
		return -1
	if n3 + n2 < k:
		return -1
	ap = [0]
	for i in range(n1):
		ap.append(ap[-1] + a[i])
	ap.append(0)
	bp = [0]
	for i in range(n2):
		bp.append(bp[-1] + b[i])
	bp.append(0)
	start = max(max(0, k - n1), max(0, k - n2))
	s = 0
	for i in range(start):
		s += common[i]
	common.append(0)
	ans = 10000000000.0
	for i in range(start, min(k, n3) + 1):
		ans = min(ans, s + ap[k - i] + bp[k - i])
		s += common[i]
	return ans
(n, k) = map(int, input().split())
(a, b, common) = ([], [], [])
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x and y:
		common.append(t)
	elif x == 1 and y == 0:
		a.append(t)
	elif x == 0 and y == 1:
		b.append(t)
common.sort()
a.sort()
b.sort()
(n1, n2, n3) = (len(a), len(b), len(common))
print(answer())


a = input().split(' ')
list1 = []
list2 = []
list3 = []
for i in range(int(a[0])):
	b = input().split(' ')
	if b[1] == '1':
		if b[2] == '1':
			list1.append(int(b[0]))
		else:
			list2.append(int(b[0]))
	elif b[2] == '1':
		list3.append(int(b[0]))
if len(list1) + min(len(list2), len(list3)) < int(a[1]):
	print(-1)
else:
	ans = 0
	ans1 = 0
	ans2 = 0
	list1_index = 0
	list2_index = 0
	list3_index = 0
	list1_len = len(list1)
	list2_len = len(list2)
	list3_len = len(list3)
	list1.sort()
	list2.sort()
	list3.sort()
	while ans < int(a[1]) or ans1 < int(a[1]):
		if ans < int(a[1]) and ans1 < int(a[1]) and (list1_index < list1_len):
			if list2_len <= list2_index or list3_len <= list3_index:
				tag = int(a[1]) - min(ans, ans1)
				ans2 += sum(list1[list1_index:list1_index + tag])
				ans = int(a[1])
				ans1 = int(a[1])
			elif list1[list1_index] > list2[list2_index] + list3[list3_index]:
				ans1 += 1
				ans += 1
				ans2 += list2[list2_index] + list3[list3_index]
				list2_index += 1
				list3_index += 1
			else:
				ans1 += 1
				ans += 1
				ans2 += list1[list1_index]
				list1_index += 1
		elif ans < int(a[1]):
			if list2_len <= list2_index:
				ans += 1
				ans2 += list1[list1_index]
				list1_index += 1
			else:
				ans += 1
				ans2 += list2[list2_index]
				list2_index += 1
		elif ans1 < int(a[1]):
			if list3_len <= list3_index:
				ans1 += 1
				ans2 += list1[list1_index]
				list1_index += 1
			else:
				ans1 += 1
				ans2 += list3[list3_index]
				list3_index += 1
	print(ans2)


from sys import stdin
input = lambda : stdin.readline().rstrip('\r\n')
from collections import defaultdict as vector
from collections import deque as que
inin = lambda : int(input())
inar = lambda : list(map(int, input().split()))
from heapq import heappush as hpush, heappop as hpop
bob = []
alice = []
both = []
(n, k) = inar()
for i in range(n):
	(t, a, b) = inar()
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
	else:
		continue
both.sort(reverse=True)
alice.sort(reverse=True)
bob.sort(reverse=True)

def top(x):
	if x == []:
		return float('inf')
	else:
		return x[-1]
t = 0
donealice = 0
donebob = 0
while donealice < k or donebob < k:
	if both == [] and alice == [] and (bob == []):
		t = -1
		break
	if top(both) < top(alice) + top(bob):
		donealice += 1
		donebob += 1
		t += both.pop()
	else:
		if alice:
			t += alice.pop()
			donealice += 1
		if bob:
			t += bob.pop()
			donebob += 1
print(t)


(n, k) = list(map(int, input().split()))
a = []
b = []
comb = []
for _ in range(n):
	arr = list(map(int, input().split()))
	if arr[1] == 1 and arr[2] == 1:
		comb.append(arr[0])
	elif arr[1] == 1:
		a.append(arr[0])
	elif arr[2] == 1:
		b.append(arr[0])
if len(a) + len(comb) < k or len(b) + len(comb) < k:
	print(-1)
	exit()
a.sort()
b.sort()
comb.sort()
ans = 0
cnt = 0
i = 0
j = 0
sep = min(len(a), len(b))
joint = len(comb)
while cnt < k:
	if i >= sep:
		ans += comb[j]
		j += 1
		cnt += 1
	elif j >= joint:
		ans += a[i] + b[i]
		i += 1
		cnt += 1
	elif a[i] + b[i] <= comb[j]:
		ans += a[i] + b[i]
		i += 1
		cnt += 1
	else:
		ans += comb[j]
		j += 1
		cnt += 1
print(ans)


(n, k) = map(int, input().split())
a = []
b = []
c = []
at = 0
bt = 0
alo = 0
blo = 0
clo = 0
for i in range(n):
	(t, al, bl) = map(int, input().split())
	if al == 1 and bl == 1:
		at += 1
		bt += 1
		clo += 1
		c.append(t)
	elif al == 1:
		at += 1
		alo += 1
		a.append(t)
	elif bl == 1:
		bt += 1
		blo += 1
		b.append(t)
if at < k or bt < k:
	print('-1')
else:
	total = 0
	time = 0
	a.sort()
	b.sort()
	c.sort()
	j = 0
	r = 0
	while total < k:
		if j == alo or j == blo:
			time = time + c[r]
			r += 1
		elif r == clo:
			time = time + a[j] + b[j]
			j += 1
		elif a[j] + b[j] < c[r]:
			time = time + a[j] + b[j]
			j += 1
		else:
			time = time + c[r]
			r += 1
		total += 1
	print(time)


from sys import stdin, stdout
input = stdin.readline
(n, k) = map(int, input().split())
com = []
a = []
b = []
for _ in range(n):
	(t, ai, bi) = map(int, input().split())
	if ai == 1 == bi:
		com += [t]
	elif ai == 1:
		a += [t]
	elif bi == 1:
		b += [t]
a.sort(reverse=True)
b.sort(reverse=True)
com.sort(reverse=True)
(ak, bk) = (0, 0)
ans = 0
while ak != k and bk != k:
	if a and b and com:
		if a[-1] + b[-1] <= com[-1]:
			ans += a[-1] + b[-1]
			a.pop()
			b.pop()
		else:
			ans += com[-1]
			com.pop()
		ak += 1
		bk += 1
	elif a and b:
		ans += a[-1] + b[-1]
		a.pop()
		b.pop()
		ak += 1
		bk += 1
	elif com:
		ans += com[-1]
		com.pop()
		ak += 1
		bk += 1
	else:
		print(-1)
		break
else:
	print(ans)


(n, k) = map(int, input().split())
data = []
a_num = 0
b_num = 0
a_array = []
b_array = []
ab_array = []
time_sum = 0
for i in range(n):
	(time, a, b) = map(int, input().split())
	if a and b:
		a_num += 1
		b_num += 1
		ab_array.append(time)
	elif a:
		a_num += 1
		a_array.append(time)
	elif b:
		b_num += 1
		b_array.append(time)
if a_num < k or b_num < k:
	print(-1)
else:
	a_array.sort()
	b_array.sort()
	while a_array and b_array:
		ab_array.append(a_array.pop(0) + b_array.pop(0))
	ab_array.sort()
	for i in range(k):
		time_sum += ab_array[i]
	print(time_sum)


(n, k) = map(int, input().split())
lst = []
for i in range(n):
	lst.append(list(map(int, input().split())))
alice = []
bob = []
same = []
for i in lst:
	if i[1] == 1 and i[2] == 0:
		alice.append(i[0])
	elif i[2] == 1 and i[1] == 0:
		bob.append(i[0])
	elif i[2] == 1 and i[1] == 1:
		same.append(i[0])
a = len(alice)
b = len(bob)
s = len(same)
if a + s < k or b + s < k:
	print(-1)
else:
	alice.sort()
	bob.sort()
	same.sort()
	l = 0
	n = 0
	ans = 0
	count = 0
	temp = min(a, b)
	while count < k and n < s and (l < temp):
		if alice[l] + bob[l] < same[n] or n >= s:
			ans += alice[l] + bob[l]
			l += 1
			count += 1
		else:
			ans += same[n]
			count += 1
			n += 1
	if count != k and n == s:
		ans += sum(alice[l:l + k - count]) + sum(bob[l:l + k - count])
	else:
		ans += sum(same[n:n + k - count])
	print(ans)


def func():
	(n, k) = map(int, input().split())
	(sa, sb, both) = ([], [], [])
	for _ in range(n):
		(t, aLike, bLike) = map(int, input().split())
		if aLike and bLike:
			both.append(t)
		elif aLike:
			sa.append(t)
		elif bLike:
			sb.append(t)
	sa.sort()
	sb.sort()
	both.sort()
	if min(len(sa), len(sb)) + len(both) < k:
		print(-1)
		return
	ans = 2 ** 32
	common = 0 if len(sa) >= k and len(sb) >= k else k - min(len(sa), len(sb))
	cur = sum(both[:common]) + sum(sa[:k - common]) + sum(sb[:k - common])
	ans = min(cur, ans)
	while common < min(k, len(both)):
		cur = cur + both[common] - sa[k - common - 1] - sb[k - common - 1]
		ans = min(cur, ans)
		common += 1
	print(ans)
func()


(n, k) = map(int, input().split())
(both, alice, bob) = ([], [], [])
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1 and b == 0:
		alice.append(t)
	elif a == 0 and b == 1:
		bob.append(t)
both.sort(reverse=True)
alice.sort(reverse=True)
bob.sort(reverse=True)
cnt = time = 0
while cnt < k and both and alice and bob:
	if both[-1] <= alice[-1] + bob[-1]:
		time += both.pop()
	else:
		time += alice.pop() + bob.pop()
	cnt += 1
while cnt < k and both:
	time += both.pop()
	cnt += 1
while cnt < k and alice and bob:
	time += alice.pop() + bob.pop()
	cnt += 1
if cnt >= k:
	print(time)
else:
	print(-1)


z = input
mod = 10 ** 9 + 7
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)
for _ in range(1):
	(n, k) = map(int, z().split())
	a = []
	b = []
	them = []
	(ta, tb, th) = (0, 0, 0)
	for _ in range(n):
		(c, d, e) = map(int, z().split())
		if d == 1 and e == 1:
			them.append(c)
			th += 1
			continue
		if d == 1:
			a.append(c)
			ta += 1
			continue
		if e == 1:
			b.append(c)
			tb += 1
	a = sorted(a)
	b = sorted(b)
	them = sorted(them)
	for i in range(min(ta, tb)):
		them.append(a[i] + b[i])
	if len(them) < k:
		print(-1)
	else:
		them = sorted(them)
		print(sum(them[:k]))


(n, k, *f) = map(int, open(0).read().split())
books = [f[i * 3:i * 3 + 3] for i in range(n)]
a = []
b = []
ab = []
ans = float('inf')
for x in books:
	if x[1] == 1:
		if x[2] == 1:
			ab.append(x[0])
		else:
			a.append(x[0])
	elif x[2] == 1:
		b.append(x[0])
m = min(len(a), len(b))
if m + len(ab) >= k:
	a.sort()
	b.sort()
	ab.sort()
	csa = [0]
	for i in range(len(a)):
		csa.append(csa[i] + a[i])
	csb = [0]
	for i in range(len(b)):
		csb.append(csb[i] + b[i])
	csab = [0]
	for i in range(len(ab)):
		csab.append(csab[i] + ab[i])
	for i in range(max(0, k - m), min(k, len(ab)) + 1):
		ans = min(ans, csab[i] + csa[k - i] + csb[k - i])
	print(ans)
else:
	print(-1)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import sys

def solve(n, k, TAB):
	(A, B, AB) = ([], [], [])
	(cnt_a, cnt_b) = (0, 0)
	for (t, a, b) in TAB:
		cnt_a += a
		cnt_b += b
		if a * b == 1:
			AB.append(t)
		elif a == 1:
			A.append(t)
		elif b == 1:
			B.append(t)
	if cnt_a < k or cnt_b < k:
		return -1
	AB.sort()
	A.sort()
	B.sort()
	AB = AB[:min(k, len(AB))]
	l = len(AB)
	remain = k - l
	ans = sum(AB) + sum(A[:remain]) + sum(B[:remain])
	tmp = ans
	for i in range(min(l, len(A) - remain, len(B) - remain)):
		tmp -= AB.pop()
		tmp += A[remain + i] + B[remain + i]
		ans = min(ans, tmp)
	return ans

def main():
	(n, k) = map(int, input().split())
	TAB = [list(map(int, input().split())) for _ in range(n)]
	ans = solve(n, k, TAB)
	sys.stdout.write(str(ans) + '\n')
main()


def solve():
	(n, k) = map(int, input().split())
	a1 = []
	b1 = []
	ab1 = []
	for i in range(n):
		(t, a, b) = map(int, input().split())
		if a == 1 and b == 1:
			ab1.append(t)
		elif a == 1:
			a1.append(t)
		elif b == 1:
			b1.append(t)
	a1.sort()
	b1.sort()
	for i in range(min(len(a1), len(b1))):
		ab1.append(a1[i] + b1[i])
	ab1.sort()
	p = 0
	qq = len(ab1)
	if qq < k:
		print(-1)
	else:
		ans = 0
		for i in range(k):
			ans += ab1[i]
		print(ans)
for i in range(1):
	solve()


l = input().split()
n = int(l[0])
k = int(l[1])
l = []
arrboth = []
arralice = []
arrbob = []
for i in range(n):
	lo = input().split()
	x = int(lo[0])
	u = int(lo[1])
	v = int(lo[2])
	if u == 1 and v == 1:
		arrboth.append(x)
	elif u == 1:
		arralice.append(x)
	elif v == 1:
		arrbob.append(x)
arrbob.sort()
arralice.sort()
arrboth.sort()
pref1 = [0 for i in range(len(arrboth) + 1)]
pref2 = [0 for i in range(len(arralice) + 1)]
pref3 = [0 for i in range(len(arrbob) + 1)]
sumi = 0
for i in range(1, len(arrboth) + 1):
	sumi += arrboth[i - 1]
	pref1[i] = sumi
sumi = 0
for i in range(1, len(arrbob) + 1):
	sumi += arrbob[i - 1]
	pref3[i] = sumi
sumi = 0
for i in range(1, len(arralice) + 1):
	sumi += arralice[i - 1]
	pref2[i] = sumi
z = []
for i in range(min(len(arrboth), k) + 1):
	if k - i > len(arrbob) or k - i > len(arralice):
		continue
	z.append(pref1[i] + pref2[k - i] + pref3[k - i])
if z == []:
	print(-1)
else:
	print(min(z))


(n, k) = map(int, input().split())
l1 = []
l2 = []
l3 = []
(ac, bc) = (0, 0)
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		l1.append(t)
		ac += 1
		bc += 1
	elif a == 1 and b == 0:
		l2.append(t)
		ac += 1
	elif a == 0 and b == 1:
		l3.append(t)
		bc += 1
if ac < k or bc < k:
	print(-1)
else:
	l2.sort()
	l3.sort()
	ans = 0
	for i in range(min(len(l2), len(l3))):
		l1.append(l2[i] + l3[i])
	l1.sort()
	for i in range(k):
		ans += l1[i]
	print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x - 1)

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = 0
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = 1
			break
	return ans

def sieve_of_eratosthenes(n):
	ans = []
	arr = [1] * (n + 1)
	(arr[0], arr[1], i) = (0, 0, 2)
	while i * i <= n:
		if arr[i] == 1:
			j = i + i
			while j <= n:
				arr[j] = 0
				j += i
		i += 1
	for k in range(n):
		if arr[k] == 1:
			ans.append(k)
	return ans

def nc2(x):
	if x == 1:
		return 0
	else:
		return x * (x - 1) // 2

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = max(sum_so_far, current_sum)
	return sum_so_far
from math import *
for _ in range(1):
	(n, k) = map(int, input().split())
	li = []
	both = []
	ff = []
	ss = []
	(a, b) = (0, 0)
	for i in range(n):
		(f, s, t) = map(int, input().split())
		if s == 1 and t == 1:
			both.append(f)
			a += 1
			b += 1
		elif s == 0 and t == 1:
			ss.append(f)
			b += 1
		elif s == 1 and t == 0:
			ff.append(f)
			a += 1
	if a < k or b < k:
		print(-1)
	else:
		ss.sort()
		ff.sort()
		for i in range(min(len(ss), len(ff))):
			both.append(ss[i] + ff[i])
		both.sort()
		sumi = 0
		for i in range(k):
			sumi += both[i]
		print(sumi)


import atexit
import io
import sys
import math
from collections import defaultdict, Counter
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
(n, k) = map(int, input().split())
c1 = 0
c2 = 0
l1 = []
l2 = []
l = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	c1 += a
	c2 += b
	if a + b == 2:
		l.append(t)
		continue
	if a == 1:
		l1.append(t)
	if b == 1:
		l2.append(t)
if c1 < k or c2 < k:
	print(-1)
else:
	l1.sort()
	l2.sort()
	l += [a + b for (a, b) in zip(l1, l2)]
	l.sort()
	print(sum(l[:k]))


def main():
	(n, k) = list(map(int, input().split()))
	l = []
	c1 = 0
	c2 = 0
	for j in range(0, n):
		l1 = list(map(int, input().split()))
		if l1[1] == 1:
			c1 += 1
		if l1[2] == 1:
			c2 += 1
		l.append(l1)
	if c1 < k or c2 < k:
		print(-1)
		return
	c = 0
	d = {}
	l2 = []
	l3 = []
	l4 = []
	for j in range(0, n):
		if l[j][1] == 1 and l[j][2] == 1:
			l4.append(l[j][0])
		elif l[j][1] == 1:
			l2.append(l[j][0])
		elif l[j][2] == 1:
			l3.append(l[j][0])
	m = 10 ** 9 + 7
	l2.append(m)
	l3.append(m)
	l4.append(m)
	l2.sort()
	l3.sort()
	l4.sort()
	p1 = 0
	p2 = 0
	p3 = 0
	f = 0
	k1 = k
	k2 = k
	j = 0
	while k1 != 0 or k2 != 0:
		if l2[p1] + l3[p2] >= l4[p3] and p3 != len(l4) - 1:
			c += l4[p3]
			if p3 != len(l4) - 1:
				p3 += 1
			k1 -= 1
			k2 -= 1
		else:
			if k1 != 0 and p1 != len(l2) - 1:
				c += l2[p1]
				if p1 != len(l2) - 1:
					p1 += 1
				k1 -= 1
			if k2 != 0 and p2 != len(l3) - 1:
				c += l3[p2]
				if p2 != len(l3) - 1:
					p2 += 1
				k2 -= 1
		if k1 == 0 and k2 == 0:
			break
	print(c)
t = 1
for i in range(0, t):
	main()


(n, k) = map(int, input().split())
alice = []
bob = []
both = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == b == 1:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
alen = len(alice)
blen = len(bob)
mini = min(alen, blen)
alice.sort()
bob.sort()
result = []
bot_taken = 0
ab = []
for i in range(mini):
	ab.append(alice[i] + bob[i])
last_list = ab + both
last_list.sort()
if len(last_list) < k:
	print(-1)
else:
	print(sum(last_list[:k]))


(n, m, k) = input().split(' ')
(n, m, k) = (int(n), int(m), int(k))
A = []
B = []
C = []
D = []
Ainmax = 0
Binmax = 0
Cinmax = 0
Dinmax = 0
for i in range(n):
	entry = input().split(' ')
	if entry[1] == '1' and entry[2] == '1':
		C.append([int(entry[0]), i + 1])
		Cinmax += 1
	elif entry[1] == '1' and entry[2] == '0':
		A.append([int(entry[0]), i + 1])
		Ainmax += 1
	elif entry[1] == '0' and entry[2] == '1':
		B.append([int(entry[0]), i + 1])
		Binmax += 1
	else:
		D.append([int(entry[0]), i + 1])
		Dinmax += 1
A.sort(key=lambda x: x[0])
B.sort(key=lambda x: x[0])
C.sort(key=lambda x: x[0])
D.sort(key=lambda x: x[0])
mi = min(Ainmax, Binmax)
if len(C) + mi < k:
	print(-1)
elif len(C) < k and 2 * k - len(C) > m:
	print(-1)
else:
	time = 0
	Ain = 0
	Bin = 0
	Cin = 0
	Din = 0
	ABinmax = min(mi, m - k)
	for i in range(k):
		if Ain == ABinmax:
			Cin += 1
		elif Cin == Cinmax or A[Ain][0] + B[Bin][0] <= C[Cin][0]:
			Ain += 1
			Bin += 1
		else:
			Cin += 1
	for i in range(m - Ain - Bin - Cin):
		pot = []
		if Ain < Ainmax:
			pot.append([A[Ain][0], 'Ain+=1'])
		if Bin < Binmax:
			pot.append([B[Bin][0], 'Bin+=1'])
		if Cin < Cinmax:
			pot.append([C[Cin][0], 'Cin+=1'])
		if Din < Dinmax:
			pot.append([D[Din][0], 'Din+=1'])
		if Ain < Ainmax and Bin < Binmax and (Cin != 0):
			pot.append([A[Ain][0] + B[Bin][0] - C[Cin - 1][0], 'Ain+=1;Bin+=1;Cin-=1'])
		minpot = 0
		for j in range(len(pot) - 1):
			if pot[minpot][0] > pot[j + 1][0]:
				minpot = j + 1
		exec(pot[minpot][1])
	for i in range(Ain):
		time += A[i][0]
	for i in range(Bin):
		time += B[i][0]
	for i in range(Cin):
		time += C[i][0]
	for i in range(Din):
		time += D[i][0]
	print(time)
	for i in range(Ain):
		print(A[i][1], end=' ')
	for i in range(Bin):
		print(B[i][1], end=' ')
	for i in range(Cin):
		print(C[i][1], end=' ')
	for i in range(Din):
		print(D[i][1], end=' ')


import sys

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
(N, K) = MAP()
A = [INF]
B = [INF]
AB = [INF]
for i in range(N):
	(t, a, b) = MAP()
	if a == b == 1:
		AB.append(t)
	elif a == 1:
		A.append(t)
	elif b == 1:
		B.append(t)
A.sort(reverse=1)
B.sort(reverse=1)
AB.sort(reverse=1)
ans = 0
for i in range(K):
	if AB[-1] <= A[-1] + B[-1]:
		ans += AB.pop()
	else:
		ans += A.pop() + B.pop()
	if ans >= INF:
		print(-1)
		exit()
print(ans)


(N, K) = map(int, input().split())
T = []
A = []
B = []
O = []
for b in range(N):
	(v, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		T.append(v)
	elif a == 1:
		A.append(v)
	elif b == 1:
		B.append(v)
	else:
		O.append(v)
A.sort()
B.sort()
S = []
for i in range(min(len(A), len(B))):
	S.append(A[i] + B[i])
R = S + T
if len(R) >= K:
	R.sort()
	print(sum(R[:K]))
else:
	print(-1)


import math
import os
import random
import re
import sys
from collections import defaultdict
a = [int(x) for x in input().split()]
(n, k) = (a[0], a[1])
ara = []
for i in range(n):
	ara.append([int(x) for x in input().split()])
ara = sorted(ara, key=lambda x: x[0])
newAra = []
tmpAra1 = []
tmpAra2 = []
for i in range(n):
	if ara[i][1] == 1 and ara[i][2] == 1:
		newAra.append(ara[i])
	elif ara[i][1] == 1:
		tmpAra1.append(ara[i])
	elif ara[i][2] == 1:
		tmpAra2.append(ara[i])
for i in range(min(len(tmpAra1), len(tmpAra2))):
	newAra.append([tmpAra1[i][0] + tmpAra2[i][0], 1, 1])
newAra = sorted(newAra, key=lambda x: x[0])
if len(newAra) < k:
	print(-1)
else:
	cnt = 0
	for i in range(k):
		cnt += newAra[i][0]
	print(cnt)


def main():
	(n, k) = [int(x) for x in input().split()]
	(alice, bob) = (0, 0)
	(both, j_a, j_b) = ([], [], [])
	for i in range(n):
		b = [int(x) for x in input().split()]
		if b[1] + b[2] == 2:
			both.append(b)
		elif b[1] == 1:
			j_a.append(b)
		elif b[2] == 1:
			j_b.append(b)
	j_a.sort()
	j_b.sort()
	for i in range(min(len(j_a), len(j_b))):
		b = [j_a[i][0] + j_b[i][0], 1, 1]
		both.append(b)
	if len(both) < k:
		return -1
	both.sort()
	return sum([b[0] for b in both[:k]])
print(main())


def modinv(n, p):
	return pow(n, p - 2, p)

def main():
	(n, k) = [int(x) for x in input().split()]
	alice = []
	bob = []
	both = []
	for i in range(n):
		(t, a, b) = [int(x) for x in input().split()]
		if a == 1 and b == 1:
			both.append(t / 2)
		elif a == 1:
			alice.append(t)
		elif b == 1:
			bob.append(t)
		else:
			pass
	alice.sort()
	bob.sort()
	both.sort()
	k_alice = k
	k_bob = k
	final_t = 0
	i = 0
	j = 0
	k = 0
	p = len(alice)
	q = len(bob)
	r = len(both)
	for i in range(k + 1):
		alice.append(99999)
		bob.append(99999)
		both.append(99999)
	t = 0
	break_flag = False
	t = 0
	impossible = False
	while k_alice > 0 and k_bob > 0:
		if 2 * both[k] <= alice[i] + bob[j]:
			inc = int(2 * both[k])
			if inc >= 99999:
				impossible = True
				print(-1)
				return
			t += inc
			k += 1
		else:
			inc = 0
			inc += alice[i]
			inc += bob[j]
			if inc >= 99999:
				impossible = True
				print(-1)
				return
			t += inc
			i += 1
			j += 1
		k_bob -= 1
		k_alice -= 1
	while k_alice > 0:
		if alice[i] <= int(2 * both[j]):
			inc = alice[i]
			if inc >= 99999:
				impossible = True
				print(-1)
				return
			t += inc
			i += 1
		else:
			inc = int(both[k] * 2)
			if inc >= 99999:
				impossible = True
				print(-1)
				return
			t += inc
			k += 1
		k_alice -= 1
	while k_bob > 0:
		if bob[j] <= int(2 * both[k]):
			inc = bob[j]
			if inc >= 99999:
				impossible = True
				print(-1)
				return
			t += inc
			j += 1
		else:
			inc = int(both[k] * 2)
			if inc >= 99999:
				impossible = True
				print(-1)
				return
			t += inc
			k += 1
		k_bob -= 1
	if impossible:
		print(-1)
	else:
		print(t)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from collections import defaultdict
(n, k) = map(int, input().split())
my_dick = {}
my_dick = defaultdict(lambda : list(), my_dick)
for i in range(n):
	(a, b, c) = map(int, input().split())
	if b + c == 2:
		my_dick[b + c].append(a)
	elif b == 0 and c == 1:
		my_dick[b + 3].append(a)
	elif c == 0 and b == 1:
		my_dick[c + 4].append(a)
my_dick[2] = sorted(my_dick[2])
my_dick[3].sort()
my_dick[4].sort()
i = 0
while len(my_dick[3]) > 0 and len(my_dick[4]) > 0:
	my_dick[2].append(my_dick[3][i] + my_dick[4][i])
	my_dick[3].remove(my_dick[3][i])
	my_dick[4].remove(my_dick[4][i])
my_dick[2].sort()
if len(my_dick[2]) >= k:
	print(sum(my_dick[2][:k]))
else:
	print('-1')


(n, k) = map(int, input().split())
(both, a, b) = ([], [], [])
for i in range(n):
	(t, al, bl) = map(int, input().split())
	if al & bl:
		both.append(t)
	elif al:
		a.append(t)
	elif bl:
		b.append(t)
a.sort()
b.sort()
for i in range(min(len(a), len(b))):
	both.append(a[i] + b[i])
print(-1 if len(both) < k else sum(sorted(both)[:k]))


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
(n, k) = map(int, input().split())
l1 = []
l2 = []
l3 = []
l4 = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		l3.append(t)
	elif a == 1 and b == 0:
		l1.append(t)
	elif a == 0 and b == 1:
		l2.append(t)
	else:
		l4.append(t)
l1.sort(reverse=True)
l2.sort(reverse=True)
l3.sort()
l4.sort()
ans = 0
t = True
if len(l1) + len(l3) < k or len(l2) + len(l3) < k:
	print(-1)
else:
	if k >= len(l3):
		if len(l3):
			ans = sum(l3)
		else:
			ans = 0
		t = False
		ln = len(l3)
	else:
		ans = sum(l3[:k])
		l3 = l3[:k]
		ln = k
	if t == True:
		if min(len(l2), len(l1)) > 0:
			while l1[-1] + l2[-1] <= l3[-1]:
				ans -= l3[-1]
				ans += l1[-1] + l2[-1]
				l1.pop()
				l2.pop()
				l3.pop()
				if len(l3) == 0 or len(l1) == 0 or len(l2) == 0:
					break
		print(ans)
	else:
		for j in range(k - ln):
			ans += l1[-1] + l2[-1]
			l1.pop()
			l2.pop()
		if min(len(l2), len(l1), len(l3)) > 0:
			while l1[-1] + l2[-1] <= l3[-1]:
				ans -= l3[-1]
				ans += l1[-1] + l2[-1]
				l1.pop()
				l2.pop()
				l3.pop()
				if len(l3) == 0 or len(l1) == 0 or len(l2) == 0:
					break
		print(ans)


import sys, math
input = sys.stdin.readline
(n, k) = map(int, input().split())
both = []
a = []
b = []
for i in range(n):
	(ti, ai, bi) = map(int, input().split())
	if ai == 1 and bi == 1:
		both.append(ti)
	elif ai == 1 and bi == 0:
		a.append(ti)
	elif ai == 0 and bi == 1:
		b.append(ti)
both.sort()
a.sort()
b.sort()
bothPointer = 0
aPointer = 0
bPointer = 0
alength = len(a)
blength = len(b)
bothlength = len(both)
ans = [0] * (k + 1)
flag = True
for i in range(1, k + 1):
	if aPointer < alength and bPointer < blength:
		if bothPointer < bothlength:
			if a[aPointer] + b[bPointer] < both[bothPointer]:
				ans[i] = ans[i - 1] + a[aPointer] + b[bPointer]
				aPointer += 1
				bPointer += 1
			else:
				ans[i] = ans[i - 1] + both[bothPointer]
				bothPointer += 1
		else:
			ans[i] = ans[i - 1] + a[aPointer] + b[bPointer]
			aPointer += 1
			bPointer += 1
	elif bothPointer < bothlength:
		ans[i] = ans[i - 1] + both[bothPointer]
		bothPointer += 1
	else:
		flag = False
		break
if flag:
	print(ans[k])
else:
	print(-1)


(n, k) = map(int, input().split())
alice = []
bob = []
both = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a & b:
		both.append(t)
	elif a:
		alice.append(t)
	elif b:
		bob.append(t)
alice.sort()
bob.sort()
for i in range(min(len(alice), len(bob))):
	both.append(alice[i] + bob[i])
print(-1 if len(both) < k else sum(sorted(both)[:k]))
exit()


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time
inf = 10 ** 20
mod = 10 ** 9 + 7

def LI():
	return list(map(int, input().split()))

def II():
	return int(input())

def LS():
	return list(input().split())

def S():
	return input()

def main():
	(n, k) = LI()
	tab = [LI() for _ in range(n)]
	both = list()
	only_a = list()
	only_b = list()
	for (t, a, b) in tab:
		if a and b:
			both.append(t)
		elif a:
			only_a.append(t)
		elif b:
			only_b.append(t)
	m = min(len(only_a), len(only_b))
	only_b.sort()
	only_a.sort()
	for i in range(m):
		tmp = only_b[i] + only_a[i]
		both.append(tmp)
	both.sort()
	if len(both) < k:
		return -1
	return sum(both[:k])
print(main())


(n, k) = map(int, input().split())
(alice, bob) = ([], [])
both = []
for _ in range(n):
	x = list(map(int, input().split()))
	if x[2] == 1 and x[1] == 1:
		both.append(x[0])
	elif x[1]:
		alice.append(x)
	elif x[2]:
		bob.append(x)
alice.sort(key=lambda x: x[0])
bob.sort(key=lambda x: x[0])
both.sort()
tgt = []
for i in range(min(len(alice), len(bob))):
	tgt.append(alice[i][0] + bob[i][0])
(p1, p2) = (0, 0)
count = 0
ans = 0
if len(tgt) + len(both) < k:
	print(-1)
else:
	while count < k:
		if p2 == len(both) or (p1 < len(tgt) and tgt[p1] <= both[p2]):
			ans += tgt[p1]
			p1 += 1
		else:
			ans += both[p2]
			p2 += 1
		count += 1
	print(ans)


import heapq
(n, k) = map(int, input().split())
both = []
alice = []
bob = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1 and b == 0:
		alice.append(t)
	elif a == 0 and b == 1:
		bob.append(t)
heapq.heapify(both)
heapq.heapify(alice)
heapq.heapify(bob)
(at, bt, count) = (0, 0, 0)
while len(both) > 0 and len(alice) > 0 and (len(bob) > 0) and (at < k) and (bt < k):
	x = heapq.heappop(both)
	y = heapq.heappop(alice)
	z = heapq.heappop(bob)
	if x < y + z:
		at += 1
		bt += 1
		count += x
		heapq.heappush(alice, y)
		heapq.heappush(bob, z)
	else:
		at += 1
		bt += 1
		count += y + z
		heapq.heappush(both, x)
if len(both) > 0 and (len(alice) == 0 or len(bob) == 0) and (at < k) and (bt < k):
	while len(both) > 0 and at < k and (bt < k):
		x = heapq.heappop(both)
		at += 1
		bt += 1
		count += x
elif len(both) == 0 and len(alice) > 0 and (len(bob) > 0) and (at < k) and (bt < k):
	while len(alice) > 0 and len(bob) > 0 and (at < k) and (bt < k):
		x = heapq.heappop(alice)
		y = heapq.heappop(bob)
		at += 1
		bt += 1
		count += x + y
if at != k or bt != k:
	print(-1)
else:
	print(count)


from collections import defaultdict
import sys, math
f = None
try:
	f = open('q1.input', 'r')
except IOError:
	f = sys.stdin
if 'xrange' in dir(__builtins__):
	range = xrange
sys.setrecursionlimit(10 ** 2)

def print_case_iterable(case_num, iterable):
	print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
	print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
	print(' '.join(A))

def read_int():
	return int(f.readline().strip())

def read_int_array():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def read_string():
	return list(f.readline().strip())

def ri():
	return int(f.readline().strip())

def ria():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def rs():
	return list(f.readline().strip())

def bi(x):
	return bin(x)[2:]
from collections import deque
import math
NUMBER = 10 ** 9 + 7

def factorial(n):
	M = NUMBER
	f = 1
	for i in range(1, n + 1):
		f = f * i % M
	return f

def mult(a, b):
	return a * b % NUMBER

def minus(a, b):
	return (a - b) % NUMBER

def plus(a, b):
	return (a + b) % NUMBER

def egcd(a, b):
	if a == 0:
		return (b, 0, 1)
	else:
		(g, y, x) = egcd(b % a, a)
		return (g, x - b // a * y, y)

def modinv(a):
	m = NUMBER
	(g, x, y) = egcd(a, m)
	if g != 1:
		raise Exception('modular inverse does not exist')
	else:
		return x % m

def choose(n, k):
	if n < k:
		assert false
	return mult(factorial(n), modinv(mult(factorial(k), factorial(n - k)))) % NUMBER
from collections import deque, defaultdict
import heapq
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def dfs(g, timeIn, timeOut, depths, parents):
	cnt = 0
	stack = [[1, 0, 0, 0]]
	while stack:
		(v, neig_i, parent, depth) = stack[-1]
		parents[v] = parent
		depths[v] = depth
		if neig_i == 0:
			timeIn[v] = cnt
			cnt += 1
		while neig_i < len(g[v]):
			u = g[v][neig_i]
			if u == parent:
				neig_i += 1
				continue
			stack[-1][1] = neig_i + 1
			stack.append([u, 0, v, depth + 1])
			break
		if neig_i == len(g[v]):
			stack.pop()
			timeOut[v] = cnt
			cnt += 1
cnt = 0

@bootstrap
def dfs(v, adj, timeIn, timeOut, depths, parents, parent=0, depth=0):
	global cnt
	parents[v] = parent
	depths[v] = depth
	timeIn[v] = cnt
	cnt += 1
	for u in adj[v]:
		if u == parent:
			continue
		yield dfs(u, adj, timeIn, timeOut, depths, parents, v, depth + 1)
	timeOut[v] = cnt
	cnt += 1
	yield

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def lcm(a, b):
	return a * b / gcd(a, b)

def get_num_2_5(n):
	twos = 0
	fives = 0
	while n > 0 and n % 2 == 0:
		n //= 2
		twos += 1
	while n > 0 and n % 5 == 0:
		n //= 5
		fives += 1
	return (twos, fives)

def solution(data, c, a, b, n, k):
	if b.count(1) < k or a.count(1) < k:
		return -1
	al = []
	bo = []
	both = []
	for i in range(n):
		if a[i] == 1 and b[i] == 1:
			both.append(c[i])
		elif a[i] == 1:
			al.append(c[i])
		elif b[i] == 1:
			bo.append(c[i])
	bo.sort(reverse=True)
	al.sort(reverse=True)
	both.sort(reverse=True)
	curr = 0
	res = 0
	inf = 10 ** 10
	while curr < k:
		both_x = both[-1] if both else inf
		al_x = al[-1] if al else inf
		bo_x = bo[-1] if bo else inf
		if both_x > al_x + bo_x:
			res += al.pop() + bo.pop()
		else:
			res += both.pop()
		curr += 1
	return res

def main():
	T = 1
	for i in range(T):
		data = []
		(n, k) = ria()
		(c, a, b) = ([], [], [])
		for j in range(n):
			(c_, a_, b_) = ria()
			c.append(c_)
			a.append(a_)
			b.append(b_)
		x = solution(data, c, a, b, n, k)
		if 'xrange' not in dir(__builtins__):
			print(x)
		else:
			(print >> output, str(x))
	if 'xrange' in dir(__builtins__):
		print(output.getvalue())
		output.close()
if 'xrange' in dir(__builtins__):
	import cStringIO
	output = cStringIO.StringIO()
main()


import sys, math
input = sys.stdin.readline

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input().strip()

def listStr():
	return list(input().strip())
import collections as col
import math

def solve():
	(N, K) = getInts()
	A = []
	B = []
	AB = []
	for n in range(N):
		(T, a, b) = getInts()
		if a and b:
			AB.append(T)
		elif a:
			A.append(T)
		elif b:
			B.append(T)
	ans = 0
	A.sort(reverse=True)
	B.sort(reverse=True)
	AB.sort(reverse=True)

	def getNextBook():
		if (not A or not B) and (not AB):
			return -1
		if (not A or not B) or (AB and AB[-1] <= A[-1] + B[-1]):
			return AB.pop()
		return A.pop() + B.pop()
	count = 0
	while True:
		x = getNextBook()
		if x < 0:
			return -1
		ans += x
		count += 1
		if count == K:
			return ans
print(solve())


from collections import Counter
(n, k) = map(int, input().split())
dat = [list(map(int, input().split())) for _ in range(n)]
x = [v for (v, a, b) in dat if a and b]
y = [v for (v, a, b) in dat if a and (not b)]
z = [v for (v, a, b) in dat if not a and b]
x.extend((u + v for (u, v) in zip(sorted(y), sorted(z))))
if len(x) < k:
	print(-1)
else:
	print(sum(sorted(x)[:k]))


import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f
from copy import *
from bisect import *
from heapq import *
from math import *
from itertools import permutations

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

def li():
	return [int(x) for x in input().split()]

def fi():
	return int(input())

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)

def bo(i):
	return ord(i) - ord('a')
(n, k) = mi()
a = []
for i in range(n):
	p = li()
	a.append(p)
a.sort()
c = d = ans = 0
c1 = []
d1 = []
r = 0
for i in range(n):
	if a[i][1:] == [0, 1]:
		if d + r >= k:
			continue
		ans += a[i][0]
		d1.append(a[i][0])
		d += 1
	elif a[i][1:] == [1, 0]:
		if c + r >= k:
			continue
		ans += a[i][0]
		c1.append(a[i][0])
		c += 1
	elif a[i][1:] == [1, 1]:
		if c + r >= k and d + r >= k and (len(c1) + len(d1) > 1):
			if c1[-1] + d1[-1] > a[i][0]:
				r += 1
				c -= 1
				d -= 1
				ans -= c1[-1] + d1[-1]
				ans += a[i][0]
				c1.pop()
				d1.pop()
				continue
		if c + r < k or d + r < k:
			r += 1
			ans += a[i][0]
		if c + r > k:
			ans -= c1[-1]
			c -= 1
			c1.pop()
		if d + r > k:
			ans -= d1[-1]
			d -= 1
			d1.pop()
	if r >= k:
		break
print(ans if c + r >= k and d + r >= k else -1)


(n, k) = map(int, input().split())
ar = []
a1 = []
b1 = []
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		ar.append(t)
	elif a == 1 and b == 0:
		a1.append(t)
	elif b == 1 and a == 0:
		b1.append(t)
a1 = sorted(a1)
b1 = sorted(b1)
for i in range(min(len(a1), len(b1))):
	ar.append(a1[i] + b1[i])
ar = sorted(ar)
if len(ar) < k:
	print(-1)
else:
	print(sum(ar[:k]))


import sys
from collections import defaultdict
input = lambda : sys.stdin.readline().strip()
(n, k) = map(int, input().split())
a = []
b = []
c = []
for i in range(n):
	(ti, ai, bi) = map(int, input().split())
	if ai == 0 and bi == 1:
		a.append(ti)
	elif ai == 1 and bi == 0:
		b.append(ti)
	elif ai == 1 and bi == 1:
		c.append(ti)
a.sort()
b.sort()
c.sort()
for i in range(1, len(a)):
	a[i] += a[i - 1]
for i in range(1, len(b)):
	b[i] += b[i - 1]
for i in range(1, len(c)):
	c[i] += c[i - 1]
c = [0] + c
ans = float('inf')
for i in range(len(c)):
	rem = k - i
	if i == k:
		ans = min(ans, c[i])
	if rem - 1 >= 0 and rem <= min(len(a), len(b)):
		ans = min(ans, c[i] + a[rem - 1] + b[rem - 1])
if ans == float('inf'):
	print(-1)
else:
	print(ans)


import atexit
import io
import sys
import math
from collections import defaultdict, Counter
(n, k) = map(int, input().split())
c1 = 0
c2 = 0
l1 = []
l2 = []
l = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	c1 += a
	c2 += b
	if a + b == 2:
		l.append(t)
		continue
	if a == 1:
		l1.append(t)
	if b == 1:
		l2.append(t)
if c1 < k or c2 < k:
	print(-1)
else:
	l1.sort()
	l2.sort()
	l += [a + b for (a, b) in zip(l1, l2)]
	l.sort()
	print(sum(l[:k]))


(n, k) = map(int, input().split())
books = []
alice = set()
bob = set()
for i in range(n):
	books.append([int(i) for i in input().split()])
	if books[-1][1] == 1:
		alice.add(i)
	if books[-1][2] == 1:
		bob.add(i)
if len(alice) < k or len(bob) < k:
	print(-1)
else:
	(time, a, b) = (0, 0, 0)
	temp = alice | bob
	diff = temp.difference(alice & bob)
	temp_alice = []
	temp_bob = []
	for i in diff:
		if i in alice:
			temp_alice += [books[i]]
		else:
			temp_bob += [books[i]]
	temp_alice.sort()
	temp_bob.sort()
	temp_mass = []
	for i in range(min(len(temp_bob), len(temp_alice))):
		temp_mass.append([temp_alice[i][0] + temp_bob[i][0], 1, 1])
	temp_mass = temp_mass + [books[i] for i in temp if i not in diff]
	temp_mass.sort(key=lambda x: (x[1] + x[2], -x[0]), reverse=True)
	for i in temp_mass:
		time += i[0]
		a += i[1]
		b += i[2]
		if a >= k and b >= k:
			break
	print(time)


(n, k) = [int(i) for i in input().split()]
a = []
b = []
t = []
for i in range(n):
	(ti, ai, bi) = [int(i) for i in input().split()]
	t.append([ti, i])
	a.append(ai)
	b.append(bi)
temp = 0
if a.count(1) < k or b.count(1) < k:
	temp = 1
	print(-1)
if temp == 0:
	alice = []
	bob = []
	both = []
	for i in range(n):
		if a[i] == 1 and b[i] == 0:
			alice.append(t[i][0])
		if b[i] == 1 and a[i] == 0:
			bob.append(t[i][0])
		if a[i] == 1 and b[i] == 1:
			both.append(t[i][0])
	alice.sort()
	bob.sort()
	both.sort()
	alice.reverse()
	bob.reverse()
	both.reverse()
	(aa, bb) = (k, k)
	ans = 0
	while aa and bb:
		if len(both) > 0:
			if len(alice) > 0 and len(bob) > 0:
				if both[-1] <= alice[-1] + bob[-1]:
					aa -= 1
					bb -= 1
					ans += both[-1]
					both.pop()
				else:
					aa -= 1
					bb -= 1
					ans += alice[-1] + bob[-1]
					alice.pop()
					bob.pop()
			else:
				aa -= 1
				bb -= 1
				ans += both[-1]
				both.pop()
		else:
			aa -= 1
			bb -= 1
			ans += alice[-1] + bob[-1]
			alice.pop()
			bob.pop()
	if aa > 0:
		for i in range(aa):
			ans += alice[len(alice) - 1 - i]
	if bb > 0:
		for i in range(bb):
			ans += bob[len(bob) - 1 - i]
	print(ans)


def fn(qa, qb, qc, k):
	qa.sort()
	qb.sort()
	qc.sort()
	num = 0
	ia = ib = ic = 0
	(na, nb, nc) = (len(qa), len(qb), len(qc))
	for i in range(k):
		if nc == 0 or ic >= nc:
			num += qa[ia] + qb[ib]
			ia += 1
			ib += 1
		elif na == 0 or nb == 0 or ia >= na or (ib >= nb):
			num += qc[ic]
			ic += 1
		elif qa[ia] + qb[ib] < qc[ic]:
			num += qa[ia] + qb[ib]
			ia += 1
			ib += 1
		else:
			num += qc[ic]
			ic += 1
	print(num)
(n, k) = list(map(int, input().split(' ')))
(qa, qb, qc) = ([], [], [])
ca = cb = 0
for i in range(n):
	(t, a, b) = list(map(int, input().split(' ')))
	if a == 1 and b == 1:
		ca += 1
		cb += 1
		qc.append(t)
	elif a == 1:
		ca += 1
		qa.append(t)
	elif b == 1:
		cb += 1
		qb.append(t)
if ca < k or cb < k:
	print(-1)
else:
	fn(qa, qb, qc, k)


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def get_str():
	return input().decode().strip()

def rint():
	return map(int, input().split())

def oint():
	return int(input())
(n, k) = rint()
tab = []
for i in range(n):
	tab.append(tuple(rint()))
tab.sort()
ai = []
bi = []
bc = 0
tot_time = 0
ka = 0
kb = 0
for i in range(n):
	(t, a, b) = tab[i]
	if a and (not b):
		if ka < k:
			ka += 1
			ai.append(i)
			tot_time += t
	elif b and (not a):
		if kb < k:
			kb += 1
			bi.append(i)
			tot_time += t
	elif a and b:
		if ka < k or kb < k:
			ka += 1
			kb += 1
			tot_time += t
			if ka > k:
				if len(ai):
					ta = tab[ai.pop()][0]
					tot_time -= ta
					ka -= 1
			if kb > k:
				if len(bi):
					tb = tab[bi.pop()][0]
					tot_time -= tb
					kb -= 1
		elif ka >= k and kb >= k:
			if len(ai) and len(bi):
				ta = tab[ai.pop()][0]
				tb = tab[bi.pop()][0]
				if t < ta + tb:
					tot_time = tot_time - ta - tb + t
if ka >= k and kb >= k:
	print(tot_time)
else:
	print(-1)


(n, k) = map(int, input().split())
la = []
lb = []
lt = []
a1 = 0
b1 = 0
co = 0
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1:
		if b != 1:
			la.append(t)
		a1 = a1 + 1
	if b == 1:
		if a != 1:
			lb.append(t)
		b1 = b1 + 1
	if a == 1 and b == 1:
		lt.append(t)
if a1 < k or b1 < k:
	print(-1)
else:
	la.sort()
	lb.sort()
	v = len(lt)
	lt.sort()
	lt1 = []
	if v > k:
		for i in range(k):
			lt1.append(lt[i])
	else:
		lt1 = lt
	m = k - len(lt1)
	co = sum(lt1)
	co1 = 0
	x = len(la)
	y = len(lb)
	for i in range(k):
		if k > x or k > y:
			co1 = -1
			break
		co1 = co1 + (la[i] + lb[i])
	for i in range(m):
		if i > x or i > y:
			co = -1
			break
		co = co + (la[i] + lb[i])
	lt1.reverse()
	j = 0
	h = m
	z = len(lt1)
	while True:
		if h < x and h < y and (j < z):
			if lt1[j] > la[h] + lb[h]:
				co = co - lt1[j]
				co = co + (la[h] + lb[h])
				j = j + 1
				h = h + 1
			else:
				break
		else:
			break
	if co == -1:
		print(co1)
	elif co1 != -1:
		print(min(co, co1))
	else:
		print(co)


(n, k) = map(int, input().split())
alice = [0]
bob = [0]
common = [0]
la = 1
lb = 1
lc = 1
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		common.append(t)
		lc += 1
	elif a == 1:
		alice.append(t)
		la += 1
	elif b == 1:
		bob.append(t)
		lb += 1
alice.sort()
bob.sort()
common.sort()
alicecum = []
bobcum = []
commoncum = []
tot = 0
for num in alice:
	tot += num
	alicecum.append(tot)
tot = 0
for num in bob:
	tot += num
	bobcum.append(tot)
tot = 0
for num in common:
	tot += num
	commoncum.append(tot)
if la + lc - 2 < k or lb + lc - 2 < k:
	print(-1)
else:
	res = 100000000000055
	for i in range(k + 1):
		com = k - i
		(al, bo) = (i, i)
		if com < lc and al < la and (bo < lb):
			temp = commoncum[com]
			temp += alicecum[al]
			temp += bobcum[bo]
			res = min(res, temp)
	print(res)


l1 = input().split(' ')
n = int(l1[0])
k = int(l1[1])
alike = 0
blike = 0
total = 0
tboth = []
ta = []
tb = []
for i in range(n):
	b = input().split(' ')
	time = int(b[0])
	alice = int(b[1])
	bob = int(b[2])
	if alice:
		alike += 1
	if bob:
		blike += 1
	if alice and bob:
		tboth.append(time)
	if alice and (not bob):
		ta.append(time)
	if not alice and bob:
		tb.append(time)
if alike < k or blike < k:
	print(-1)
else:
	import heapq
	heapq.heapify(tboth)
	heapq.heapify(ta)
	heapq.heapify(tb)
	alike = blike = k
	while alike > 0 or blike > 0:
		a = b = o = False
		if tboth:
			mo = heapq.heappop(tboth)
			o = True
		if ta:
			ma = heapq.heappop(ta)
			a = True
		if tb:
			mb = heapq.heappop(tb)
			b = True
		if a and b and o:
			mi = min(ma + mb, mo)
			total += mi
			if mi == mo:
				heapq.heappush(ta, ma)
				heapq.heappush(tb, mb)
			else:
				heapq.heappush(tboth, mo)
			alike -= 1
			blike -= 1
		elif a and b:
			total += ma + mb
			alike -= 1
			blike -= 1
		elif o:
			total += mo
			alike -= 1
			blike -= 1
		elif a:
			total += ma
			alike -= 1
		elif b:
			total += mb
			blike -= 1
	print(total)


(n, k) = [int(_) for _ in input().split()]
alice = []
bob = []
both = []
for i in range(n):
	book = [int(_) for _ in input().split()]
	if book[1] == book[2] == 1:
		both.append(book[0])
	elif book[1] == 1:
		alice.append(book[0])
	elif book[2] == 1:
		bob.append(book[0])
alice.sort()
bob.sort()
both.sort()
a = b = c = t = 0
for i in range(k):
	if (a == len(alice) or b == len(bob)) and c == len(both):
		t = -1
		break
	if c < len(both) and (a == len(alice) or b == len(bob) or both[c] < alice[a] + bob[b]):
		t += both[c]
		c += 1
	else:
		t += alice[a] + bob[b]
		a += 1
		b += 1
print(t)


from sys import *
input = stdin.readline
for _ in range(1):
	(n, k) = map(int, input().split())
	c = []
	a = []
	b = []
	for _ in range(n):
		(x, y, z) = map(int, input().split())
		if y == 1 and z == 1:
			c.append(x)
		elif y == 1:
			a.append(x)
		elif z == 1:
			b.append(x)
	a.sort()
	b.sort()
	for i in range(min(len(a), len(b))):
		c.append(a[i] + b[i])
	c.sort()
	if len(c) >= k:
		print(sum(c[:k]))
	else:
		print(-1)


import math, string, itertools, operator, fractions, heapq, collections, re, array, bisect, sys, functools

def solve(line):
	(n, k) = map(int, line.split())
	a = []
	for i in range(n):
		a.append([int(x) for x in sys.stdin.readline().rstrip().split()])
	(x, y, z) = ([], [], [])
	for i in range(n):
		if a[i][1] == 1 and a[i][2] == 1:
			z.append(a[i][0])
		elif a[i][1] == 1:
			x.append(a[i][0])
		elif a[i][2] == 1:
			y.append(a[i][0])
	if len(x) + len(z) < k or len(y) + len(z) < k:
		return -1
	x.sort()
	y.sort()
	z.sort()
	ans = 0
	(i, j, k1) = (0, 0, 0)
	while k > 0:
		if i < len(x) and j < len(y) and (k1 < len(z)) and (x[i] + y[j] < z[k1]):
			ans += x[i] + y[j]
			i += 1
			j += 1
		elif k1 < len(z):
			ans += z[k1]
			k1 += 1
		else:
			ans += x[i] + y[j]
			i += 1
			j += 1
		k -= 1
	return ans
t = 0
while True:
	line = sys.stdin.readline().rstrip()
	if not line:
		break
	print(solve(line))
	t += 1


import math
import collections
from sys import stdin, stdout, setrecursionlimit
from bisect import bisect_left as bsl
from bisect import bisect_right as bsr
import heapq as hq
setrecursionlimit(2 ** 20)
T = 1
for _ in range(T):
	(n, k) = list(map(int, stdin.readline().rstrip().split()))
	(t, a, b) = ([], [], [])
	(sa, sb) = (0, 0)
	for i in range(n):
		(t1, t2, t3) = list(map(int, stdin.readline().rstrip().split()))
		t.append(t1)
		a.append(t2)
		b.append(t3)
		sa += t2
		sb += t3
	if sa < k or sb < k:
		print(-1)
		continue
	else:
		on_a = []
		on_b = []
		on_ab = []
		for i in range(n):
			if a[i] == 1 and b[i] == 1:
				on_ab.append(t[i])
			elif a[i] == 1:
				on_a.append(t[i])
			elif b[i] == 1:
				on_b.append(t[i])
		on_a.sort()
		on_b.sort()
		on_ab.sort()
		ans = 0
		(ai, bi, abi) = (0, 0, 0)
		(cnta, cntb) = (0, 0)
		while (cnta != k and cntb != k) and (ai < len(on_a) and bi < len(on_b) and (abi < len(on_ab))):
			if on_a[ai] + on_b[bi] < on_ab[abi]:
				cnta += 1
				cntb += 1
				ans += on_a[ai] + on_b[bi]
				ai += 1
				bi += 1
			else:
				cnta += 1
				cntb += 1
				ans += on_ab[abi]
				abi += 1
		if cnta == k:
			print(ans)
			continue
		elif abi < len(on_ab):
			while cnta != k:
				ans += on_ab[abi]
				abi += 1
				cnta += 1
			print(ans)
			continue
		else:
			while cnta != k:
				ans += on_a[ai]
				ai += 1
				cnta += 1
			while cntb != k:
				ans += on_b[bi]
				bi += 1
				cntb += 1
			print(ans)
			continue


(n, k) = map(int, input().split())
al = []
bob = []
both = []
for i in range(n):
	(a, b, c) = map(int, input().split())
	if b == 1 and c == 1:
		both.append(a)
	elif b == 1:
		al.append(a)
	elif c == 1:
		bob.append(a)
tp = len(both)
la = len(al)
ob = len(bob)
a = la + tp
b = ob + tp
if a < k or b < k:
	print('-1')
else:
	both.sort()
	al.sort()
	bob.sort()
	ans = 0
	c = 0
	d = 0
	for i in range(k):
		z = 20001
		m = 20001
		if c < tp:
			z = both[c]
		if d < la and d < ob:
			m = al[d] + bob[d]
		if z < m:
			ans += z
			c += 1
		else:
			ans += m
			d += 1
	print(ans)


import io
import os
from collections import Counter, defaultdict, deque

def solve(N, K, books):
	bothLikes = []
	aLikes = []
	bLikes = []
	for (t, a, b) in books:
		if a and b:
			bothLikes.append(t)
		elif a:
			aLikes.append(t)
		elif b:
			bLikes.append(t)
	if len(bothLikes) + len(aLikes) < K or len(bothLikes) + len(bLikes) < K:
		return -1
	bothLikes = sorted(bothLikes)[:K]
	pref = [0]
	for x in bothLikes:
		pref.append(pref[-1] + x)
	maxIndiv = min(K, len(aLikes), len(bLikes))
	aLikes = sorted(aLikes)[:maxIndiv]
	bLikes = sorted(bLikes)[:maxIndiv]
	best = float('inf')
	indivTime = 0
	for i in range(maxIndiv + 1):
		if K - i < len(pref):
			best = min(best, indivTime + pref[K - i])
		if i != maxIndiv:
			indivTime += aLikes[i] + bLikes[i]
	return best
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N, K) = [int(x) for x in input().split()]
books = [[int(x) for x in input().split()] for i in range(N)]
ans = solve(N, K, books)
print(ans)


(n, k) = map(int, input().split())
(x, y, z) = ([], [], [])
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == b == 1:
		x.append(t)
	elif a == 1:
		y.append(t)
	elif b == 1:
		z.append(t)
(lx, ly, lz) = (len(x), len(y), len(z))
x.sort()
y.sort()
z.sort()
(u, v) = (len(x), min(len(y), len(z)))
ans = 0
if u + v >= k:
	(i, j) = (0, 0)
	for _ in range(k):
		if i < u and j < v:
			if x[i] <= y[j] + z[j]:
				ans += x[i]
				i += 1
			else:
				ans += y[j] + z[j]
				j += 1
		elif i < u:
			ans += x[i]
			i += 1
		elif j < v:
			ans += y[j] + z[j]
			j += 1
else:
	ans = -1
print(ans)


import sys
import heapq
input = sys.stdin.readline
(n, k) = map(int, input().split())
arr = [list(map(int, input().split())) for _ in range(n)]
cnt1 = 0
cnt2 = 0
for (t, a, b) in arr:
	if a == 1:
		cnt1 += 1
	if b == 1:
		cnt2 += 1
if cnt1 < k or cnt2 < k:
	print(-1)
	exit()
arr = sorted(arr, key=lambda x: x[0])
arr = sorted(arr, reverse=True, key=lambda x: x[1])
ans = 0
cnt = 0
for i in range(k):
	ans += arr[i][0]
	if arr[i][2] == 1:
		cnt += 1
if cnt == k:
	print(ans)
	exit()
q1 = []
q2 = []
q3 = []
for (t, a, b) in arr[:k]:
	if a == 1 and b == 0:
		heapq.heappush(q1, -t)
for (t, a, b) in arr[k:]:
	if a == 1 and b == 1:
		heapq.heappush(q2, t)
	if a == 0 and b == 1:
		heapq.heappush(q3, t)
INF = 10 ** 18
while cnt < k:
	if len(q1) != 0:
		diff1 = INF
		if len(q2) != 0:
			cost1 = heapq.heappop(q1)
			heapq.heappush(q1, cost1)
			cost2 = heapq.heappop(q2)
			heapq.heappush(q2, cost2)
			diff1 = cost1 + cost2
		diff2 = INF
		if len(q3) != 0:
			cost3 = heapq.heappop(q3)
			heapq.heappush(q3, cost3)
			diff2 = cost3
		if diff1 != INF and diff2 == INF:
			ans += diff1
			heapq.heappop(q1)
			heapq.heappop(q2)
		elif diff1 == INF and diff2 != INF:
			ans += diff2
			heapq.heappop(q3)
		elif diff1 <= diff2:
			ans += diff1
			heapq.heappop(q1)
			heapq.heappop(q2)
		else:
			ans += diff2
			heapq.heappop(q3)
	else:
		diff1 = INF
		if len(q2) != 0:
			cost2 = heapq.heappop(q2)
			heapq.heappush(q2, cost2)
			diff1 = cost2
		diff2 = INF
		if len(q3) != 0:
			cost3 = heapq.heappop(q3)
			heapq.heappush(q3, cost3)
			diff2 = cost3
		if diff1 != INF and diff2 == INF:
			ans += diff1
			heapq.heappop(q2)
		elif diff1 == INF and diff2 != INF:
			ans += diff2
			heapq.heappop(q3)
		elif diff1 <= diff2:
			ans += diff1
			heapq.heappop(q2)
		else:
			ans += diff2
			heapq.heappop(q3)
	cnt += 1
print(ans)


from sys import stdin, stdout
from math import gcd, sqrt
from collections import deque
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(x)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 1 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
N = 10 ** 10 + 7
(n, k) = R()
A = []
B = []
D = []
for i in range(n):
	(t, a, b) = R()
	if a == b == 1:
		D += (t,)
	elif a:
		A += (t,)
	elif b:
		B += (t,)
A.sort()
B.sort()
for i in range(min(len(A), len(B))):
	D += (A[i] + B[i],)
D.sort()
if len(D) >= k:
	print(sum(D[:k]))
else:
	print(-1)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
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())


(n, k) = map(int, input().split())
same = []
different_a = []
different_b = []
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x == 1 and y == 1:
		same.append(t)
	elif x == 1 and y == 0:
		different_a.append(t)
	elif y == 1 and x == 0:
		different_b.append(t)
flag = 1
if len(same) + len(different_a) < k or len(same) + len(different_b) < k:
	flag = 0
if flag == 0:
	print(-1)
else:
	same.sort()
	for i in range(1, len(same)):
		same[i] += same[i - 1]
	different_a.sort()
	for i in range(1, len(different_a)):
		different_a[i] += different_a[i - 1]
	different_b.sort()
	for i in range(1, len(different_b)):
		different_b[i] += different_b[i - 1]
	i = 0
	minn = 10 ** 15
	while i <= k:
		ans1 = 10 ** 15
		if i - 1 >= 0 and i - 1 < len(same):
			ans1 = same[i - 1]
		ans2 = 10 ** 15
		if k - i - 1 >= 0 and k - i - 1 < len(different_a):
			ans2 = different_a[k - i - 1]
		ans3 = 10 ** 15
		if k - i - 1 >= 0 and k - i - 1 < len(different_b):
			ans3 = different_b[k - i - 1]
		ans = 0
		if i == 0:
			ans += ans2 + ans3
		elif i == k:
			ans += ans1
		else:
			ans += ans1 + ans2 + ans3
		minn = min(ans, minn)
		i += 1
	print(minn)


(n, k) = map(int, input().split())
(L1, L2, L3) = ([], [], [])
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a * 2 + b == 1:
		L1.append(t)
	elif a * 2 + b == 2:
		L2.append(t)
	elif a * 2 + b == 3:
		L3.append(t)
m = min(len(L1), len(L2))
if len(L3) + m < k:
	print(-1)
else:
	L1.sort()
	L2.sort()
	L3.sort()
	X = []
	for i in range(m):
		X.append(L1[i] + L2[i])
	for i in range(len(L3)):
		X.append(L3[i])
	X.sort()
	print(sum((X[i] for i in range(k))))


def compute(n, k, arr):
	add = 0
	both = []
	alice = []
	bob = []
	for i in range(n):
		if arr[i][1] and arr[i][2]:
			both.append(arr[i][0])
		elif arr[i][1]:
			alice.append(arr[i][0])
		elif arr[i][2]:
			bob.append(arr[i][0])
	both.sort()
	alice.sort()
	bob.sort()
	if len(alice) + len(both) < k or len(both) + len(bob) < k:
		return -1
	else:
		(i, j) = (0, 0)
		(n, nn, nnn) = (len(alice), len(bob), len(both))
		for _ in range(k):
			if not alice or not bob or j >= n or (j > nn) or (i < nnn and both[i] <= alice[j] + bob[j]):
				add += both[i]
				i += 1
			else:
				add += alice[j] + bob[j]
				j += 1
		return add
(n, k) = map(int, input().split())
arr = []
for _ in range(n):
	(t, a, b) = map(int, input().split())
	arr.append([t, a, b])
print(compute(n, k, arr))


from collections import Counter
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
import math
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1000000000.0) + 7
inf = float('inf')
(n, k) = gil()
(a, b, c) = ([0], [0], [0])
for _ in range(n):
	bk = gil()
	if bk[1] & bk[2]:
		c.append(bk[0])
	elif bk[1]:
		a.append(bk[0])
	elif bk[2]:
		b.append(bk[0])
a.sort()
b.sort()
c.sort()
for lst in (a, b, c):
	for i in range(2, len(lst)):
		lst[i] += lst[i - 1]
ans = inf
lmt = len(min(a, b, key=len))
for i in range(min(len(c), k + 1)):
	j = k - i
	if 0 <= j < lmt:
		ans = min(c[i] + a[j] + b[j], ans)
print(ans if ans != inf else -1)


import sys
s = sys.stdin.readline().split()
(n, k) = (int(s[0]), int(s[1]))
i = 1
arr11 = []
arr01 = []
arr10 = []
arr00 = []
while i <= n:
	s = input().split()
	s = list(map(int, s))
	if s[-1] == 0:
		if s[1] == 0:
			arr00.append(s[0])
		else:
			arr10.append(s[0])
	elif s[1] == 0:
		arr01.append(s[0])
	else:
		arr11.append(s[0])
	i += 1
arr00.sort()
arr10.sort()
arr01.sort()
arr11.sort()
arr1001 = list(map(lambda x, y: x + y, arr01, arr10))
finallst = arr1001 + arr11
finallst.sort()
i = 0
ans = 0
if len(finallst) < k:
	ans = -1
	i = k
while i < k:
	ans = ans + finallst[i]
	i += 1
print(ans)


(n, k) = list(map(int, input().split()))
al = []
bl = []
all = []
for bb in range(n):
	(t, a, b) = list(map(int, input().split()))
	if a == 1:
		if b == 1:
			all.append(t)
		else:
			al.append(t)
	elif b == 1:
		bl.append(t)
ml = min(len(al), len(bl))
if len(all) + ml < k:
	print(-1)
else:
	al = sorted(al)
	bl = sorted(bl)
	for j in range(ml):
		all.append(al[j] + bl[j])
	all = sorted(all)
	print(sum(all[:k]))


(n, k) = map(int, input().split(' '))
arr_both = []
arr_alice = []
arr_bob = []
for i in range(n):
	(t1, t2, t3) = map(int, input().split(' '))
	if t2 == 0 and t3 == 0:
		continue
	elif t2 == 1 and t3 == 1:
		arr_both.append(t1)
	elif t2 == 1:
		arr_alice.append(t1)
	else:
		arr_bob.append(t1)
i = 0
j = 0
arr_alice.sort()
arr_bob.sort()
while i < len(arr_alice) and j < len(arr_bob):
	arr_both.append(arr_alice[i] + arr_bob[j])
	i += 1
	j += 1
arr_both.sort()
if len(arr_both) < k:
	print(-1)
else:
	print(sum(arr_both[0:k]))


def main():
	(n, k) = map(int, input().split())
	a = []
	b = []
	c = []
	for _ in range(n):
		(t, first, second) = map(int, input().split())
		if first == second:
			if second == 1:
				c.append(t)
		elif first == 1:
			a.append(t)
		elif second == 1:
			b.append(t)
	if len(a) + len(c) < k or len(b) + len(c) < k:
		print(-1)
		return
	a.sort()
	b.sort()
	c.sort()
	l = 0
	r = 0
	m = 0
	ans = 0
	for i in range(k):
		if (l >= len(a) or r >= len(b)) or (m < len(c) and l < len(a) and (r < len(c)) and (c[m] < a[l] + b[r])):
			ans += c[m]
			m += 1
		else:
			ans += a[l] + b[r]
			l += 1
			r += 1
	print(ans)
	return
main()


(n, k) = map(int, input().split())
sam = []
alic = []
bob = []
for i in range(n):
	a = list(map(int, input().split()))
	if a[1] and a[2]:
		sam.append(a[0])
	elif a[1]:
		alic.append(a[0])
	elif a[2]:
		bob.append(a[0])
sam.sort()
alic.sort()
bob.sort()
q = min(len(alic), len(bob))
for i in range(q):
	sam.append(alic[i] + bob[i])
sam.sort()
ans = 0
i = 0
if k > len(sam):
	print(-1)
else:
	while i < k:
		ans += sam[i]
		i += 1
	print(ans)


def find(books, k):
	both = []
	A = []
	B = []
	for (t, a, b) in books:
		if a == 1 and b == 1:
			both += [t]
		elif a == 1:
			A += [t]
		elif b == 1:
			B += [t]
	both = sorted(both)
	A = sorted(A)
	B = sorted(B)
	ans = 10 ** 10
	num = 0
	temp = 0
	pre_both = []
	for i in range(len(both)):
		temp += both[i]
		pre_both += [temp]
	temp = 0
	pre_A = []
	for i in range(len(A)):
		temp += A[i]
		pre_A += [temp]
	temp = 0
	pre_B = []
	for i in range(len(B)):
		temp += B[i]
		pre_B += [temp]
	for num in range(min(k, len(pre_both)) + 1):
		if num > len(pre_both):
			break
		if num > 0:
			need = pre_both[num - 1]
			if num == k:
				ans = min(ans, need)
				break
		remain = k - num
		if remain > len(A):
			continue
		if remain > len(B):
			continue
		if num > 0:
			need = pre_both[num - 1] + pre_A[remain - 1] + pre_B[remain - 1]
		else:
			need = pre_A[remain - 1] + pre_B[remain - 1]
		ans = min(ans, need)
	if ans == 10 ** 10:
		return -1
	return ans
(n, k) = list(map(int, input().strip().split()))
books = []
for _ in range(n):
	(t, a, b) = list(map(int, input().strip().split()))
	books += [(t, a, b)]
print(find(books, k))


(n, k) = map(int, input().split())
a = []
b = []
c = []
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x:
		if y:
			a.append(t)
		else:
			c.append(t)
	elif y:
		b.append(t)
if len(a) + len(b) < k or len(a) + len(c) < k:
	print(-1)
else:
	mn = 10 ** 10
	a = sorted(a)
	b = sorted(b)
	c = sorted(c)
	apre = [0]
	cpre = [0]
	bpre = [0]
	for num in a:
		apre.append(apre[-1] + num)
	for num in b:
		bpre.append(bpre[-1] + num)
	for num in c:
		cpre.append(cpre[-1] + num)
	for tk in range(min(k + 1, len(a) + 1)):
		chane = k - tk
		if chane <= len(b) and chane <= len(c):
			sm = apre[tk] + bpre[chane] + cpre[chane]
			mn = min(sm, mn)
	print(mn)


def cumsum(x):
	n = len(x)
	ans = [0] * (n + 1)
	for i in range(n):
		ans[i + 1] = ans[i] + x[i]
	return ans

def solve(k, t, a, b):
	n = len(t)
	(b10, b01, b11) = ([], [], [])
	for i in range(n):
		if a[i] == 1 and b[i] == 1:
			b11.append(t[i])
		elif a[i] == 1:
			b10.append(t[i])
		elif b[i] == 1:
			b01.append(t[i])
	b10 = sorted(b10)
	b01 = sorted(b01)
	b11 = sorted(b11)
	b1 = [b10[i] + b01[i] for i in range(min(len(b10), len(b01)))]
	cs_b1 = cumsum(b1)
	cs_b11 = cumsum(b11)
	if len(b1) + len(b11) < k:
		return -1
	ans = 1e+100
	for i in range(0, k + 1):
		if i <= len(b1) and k - i <= len(b11):
			ans = min(ans, cs_b1[i] + cs_b11[k - i])
	return ans
(n, k) = map(int, input().split())
(a, b, t) = ([0] * n, [0] * n, [0] * n)
for i in range(n):
	(t[i], a[i], b[i]) = map(int, input().split())
print(solve(k, t, a, b))


(n, k) = map(int, input().split())
a = []
b = []
c = []
for i in range(n):
	(x, y, z) = map(int, input().split())
	if y == 1 and z != 1:
		a.append(x)
	elif y != 1 and z == 1:
		b.append(x)
	elif y == 1 and z == 1:
		c.append(x)
	else:
		pass
if len(a) + len(c) < k or len(c) + len(b) < k:
	ans = -1
else:
	a.sort()
	b.sort()
	c.sort()
	(pt1, pt2, pt3) = (0, 0, 0)
	move1 = 0
	move2 = 0
	ans = 0
	while True:
		if len(c) == 0:
			for i in range(k):
				ans += a[i]
			for i in range(k):
				ans += b[i]
			break
		elif move1 == k and move2 == k:
			break
		elif move1 < k and move2 == k:
			if pt1 < len(a) and pt3 < len(c):
				if a[pt1] < c[pt3]:
					ans += a[pt1]
					pt1 += 1
				else:
					ans += c[pt3]
					pt3 += 1
			elif not pt1 < len(a) and pt3 < len(c):
				ans += c[pt3]
				pt3 += 1
			else:
				ans += a[pt1]
				pt1 += 1
			move1 += 1
		elif move1 == k and move2 < k:
			if pt2 < len(b) and pt3 < len(c):
				if b[pt2] < c[pt3]:
					ans += b[pt2]
					pt2 += 1
				else:
					ans += c[pt3]
					pt3 += 1
			elif not pt2 < len(b) and pt3 < len(c):
				ans += c[pt3]
				pt3 += 1
			else:
				ans += b[pt2]
				pt2 += 1
			move2 += 1
		elif pt1 < len(a) and pt2 < len(b) and (pt3 < len(c)):
			if a[pt1] + b[pt2] < c[pt3]:
				ans += a[pt1]
				move1 += 1
				ans += b[pt2]
				move2 += 1
				pt1 += 1
				pt2 += 1
			else:
				ans += c[pt3]
				move1 += 1
				move2 += 1
				pt3 += 1
		elif pt3 < len(c):
			ans += c[pt3]
			pt3 += 1
			move1 += 1
			move2 += 1
		else:
			if pt1 < len(a):
				ans += a[pt1]
				pt1 += 1
				move1 += 1
			if pt2 < len(b):
				ans += b[pt2]
				pt2 += 1
				move2 += 1
print(ans)


(n, k) = [int(i) for i in input().split()]
doub = []
a = []
b = []
for i in range(n):
	(ti, ai, bi) = [int(i) for i in input().split()]
	if ai and bi:
		doub.append(ti)
	elif ai:
		a.append(ti)
	elif bi:
		b.append(ti)
doub.sort()
a.sort()
b.sort()
time = 0
i = 0
j = 0
while i + j < k:
	if i < len(doub):
		db = doub[i]
	else:
		db = 100000
	if j < len(a) and j < len(b):
		sing = a[j] + b[j]
	else:
		sing = 100000
	if db <= sing:
		time += db
		i += 1
	else:
		time += sing
		j += 1
if len(doub) + min(len(a), len(b)) >= k:
	print(time)
else:
	print(-1)


(n, k) = map(int, input().split())
(a, b, tog) = ([], [], [])
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x == 1 and y == 1:
		tog.append(t)
	elif x == 1 and y == 0:
		a.append(t)
	elif x == 0 and y == 1:
		b.append(t)
ltog = len(tog)
la = len(a)
lb = len(b)
if ltog + la < k or ltog + lb < k:
	print(-1)
else:
	a.sort(reverse=True)
	b.sort(reverse=True)
	tog.sort(reverse=True)
	(ca, cb) = (0, 0)
	res = 0
	while ca < k or cb < k:
		if tog:
			ptog = tog[-1]
		else:
			ptog = 0
		if a:
			pa = a[-1]
		else:
			pa = 0
		if b:
			pb = b[-1]
		else:
			pb = 0
		if ca < k and cb < k:
			if pa and pb and ptog:
				if pa + pb < ptog:
					res += pa + pb
					a.pop()
					b.pop()
				else:
					res += ptog
					tog.pop()
				ca += 1
				cb += 1
			elif ptog:
				res += ptog
				tog.pop()
				ca += 1
				cb += 1
			elif pa and pb:
				res += pa + pb
				a.pop()
				b.pop()
				ca += 1
				cb += 1
			else:
				res = -1
				break
		elif ca < k:
			if pa and ptog:
				if pa < ptog:
					res += pa
					a.pop()
					ca += 1
				else:
					res += ptog
					tog.pop()
					ca += 1
					cb += 1
			elif ptog:
				res += ptog
				tog.pop()
				ca += 1
				cb += 1
			elif pa:
				res += pa
				a.pop()
				ca += 1
			else:
				res = -1
				break
		elif cb < k:
			if pb and ptog:
				if pb < ptog:
					res += pb
					b.pop()
					cb += 1
				else:
					res += ptog
					tog.pop()
					ca += 1
					cb += 1
			elif ptog:
				res += ptog
				tog.pop()
				ca += 1
				cb += 1
			elif pb:
				res += pb
				b.pop()
				cb += 1
			else:
				res = -1
				break
	print(res)


(n, k) = map(int, input().split())
a = []
b = []
ab = []
for _ in range(n):
	(t, x, y) = map(int, input().split())
	if x == 1 and y == 1:
		ab.append(t)
	elif x == 1 and y == 0:
		a.append(t)
	elif x == 0 and y == 1:
		b.append(t)
if len(ab) + len(a) < k or len(ab) + len(b) < k:
	print(-1)
else:
	a.sort()
	a.append(float('inf'))
	b.sort()
	b.append(float('inf'))
	ab.sort()
	ab.append(float('inf'))
	tm = 0
	ia = 0
	ib = 0
	iab = 0
	books = 0
	while books < k:
		if ab[iab] <= a[ia] + b[ib]:
			tm += ab[iab]
			iab += 1
		else:
			tm += a[ia] + b[ib]
			ia += 1
			ib += 1
		books += 1
	print(tm)


def prefixSum(array):
	if len(array) == 0:
		return []
	l = [array[0]]
	for i in array[1:]:
		l.append(i + l[-1])
	return l
(n, k) = map(int, input().split())
alice = []
bob = []
both = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		both.append(t)
		continue
	if a == 1:
		alice.append(t)
	if b == 1:
		bob.append(t)
alice.sort()
bob.sort()
both.sort()
if len(alice) + len(both) < k or len(bob) + len(both) < k:
	print(-1)
elif len(alice) == 0 or len(bob) == 0:
	s = sum(both[:k])
	print(s)
else:
	bothP = prefixSum(both)
	aliceP = prefixSum(alice)
	bobP = prefixSum(bob)
	minTime = 10 ** 18
	if len(alice) >= k and len(bob) >= k:
		minTime = aliceP[k - 1] + bobP[k - 1]
	if len(both) >= k:
		minTime = min(minTime, bothP[k - 1])
	for i in range(1, k):
		if not (k - i <= len(alice) and k - i <= len(bob)):
			continue
		if i > len(both):
			continue
		elif bothP[i - 1] + aliceP[k - i - 1] + bobP[k - i - 1] < minTime:
			minTime = bothP[i - 1] + aliceP[k - i - 1] + bobP[k - i - 1]
	print(minTime)


def answer(n, k, l):
	l.sort(key=lambda x: x[0])
	a = []
	b = []
	ab = []
	for i in range(n):
		if l[i][1] == 1 and l[i][2] == 1:
			ab.append(l[i][0])
		elif l[i][1] == 1:
			a.append(l[i][0])
		elif l[i][2] == 1:
			b.append(l[i][0])
	mini = min(len(a), len(b))
	if mini + len(ab) < k:
		return -1
	t = 0
	ai = 0
	bi = 0
	abi = 0
	for i in range(k):
		if ai < len(a) and bi < len(b) and (abi < len(ab)):
			if a[ai] + b[bi] <= ab[abi]:
				t += a[ai] + b[bi]
				ai += 1
				bi += 1
			else:
				t += ab[abi]
				abi += 1
		elif ai >= len(a) or bi >= len(b):
			t += ab[abi]
			abi += 1
		elif abi >= len(ab):
			t += a[ai] + b[bi]
			ai += 1
			bi += 1
	return t
(n, k) = map(int, input().split())
l = []
for i in range(n):
	t = list(map(int, input().split()))
	l.append(t)
print(answer(n, k, l))


import sys
inp = [int(x) for x in sys.stdin.read().split()]
ii = 0
seg = [0] * 200000

def offset(x):
	return x + 100000

def encode(x, y):
	return x * 200002 + y

def decode(x):
	return (x // 200002, x % 200002)

def upd(node, L, R, pos, val):
	while L < R:
		seg[node] += val
		seg[offset(node)] += val * pos
		if L + 1 == R:
			break
		M = (L + R) // 2
		node <<= 1
		if pos < M:
			R = M
		else:
			L = M
			node += 1

def query(node, L, R, k):
	ret = 0
	while L < R:
		if k == 0:
			return ret
		if seg[node] == k:
			return ret + seg[offset(node)]
		if L + 1 == R:
			return ret + k * L
		M = (L + R) // 2
		node <<= 1
		if seg[node] >= k:
			R = M
		else:
			ret += seg[offset(node)]
			k -= seg[node]
			L = M
			node += 1
	return ret
(n, m, k) = inp[ii:ii + 3]
ii += 3
(A, B, both, neither) = ([], [], [], [])
for i in range(n):
	(t, a, b) = inp[ii:ii + 3]
	ii += 3
	if a == 0 and b == 0:
		neither.append(encode(t, i + 1))
	if a == 1 and b == 0:
		A.append(encode(t, i + 1))
	if a == 0 and b == 1:
		B.append(encode(t, i + 1))
	if a == 1 and b == 1:
		both.append(encode(t, i + 1))
	upd(1, 0, 10001, t, 1)
A.sort()
B.sort()
both.sort()
p1 = min(k, len(both))
p2 = k - p1
if 2 * k - p1 > m or p2 > min(len(A), len(B)):
	print(-1)
	exit(0)
(sum, ans, ch) = (0, 2 ** 31, p1)
for i in range(p1):
	sum += both[i] // 200002
	upd(1, 0, 10001, both[i] // 200002, -1)
for i in range(p2):
	sum += A[i] // 200002 + B[i] // 200002
	upd(1, 0, 10001, A[i] // 200002, -1)
	upd(1, 0, 10001, B[i] // 200002, -1)
ans = query(1, 0, 10001, m - 2 * k + p1) + sum
while p1 > 0:
	if p2 == min(len(A), len(B)):
		break
	upd(1, 0, 10001, A[p2] // 200002, -1)
	sum += A[p2] // 200002
	upd(1, 0, 10001, B[p2] // 200002, -1)
	sum += B[p2] // 200002
	upd(1, 0, 10001, both[p1 - 1] // 200002, 1)
	sum -= both[p1 - 1] // 200002
	p2 += 1
	p1 -= 1
	if m - 2 * k + p1 < 0:
		break
	Q = query(1, 0, 10001, m - 2 * k + p1)
	if ans > sum + Q:
		ans = sum + Q
		ch = p1
print(ans)
ind = [both[i] % 200002 for i in range(ch)] + [A[i] % 200002 for i in range(k - ch)] + [B[i] % 200002 for i in range(k - ch)]
st = neither + [both[i] for i in range(ch, len(both))] + [A[i] for i in range(k - ch, len(A))] + [B[i] for i in range(k - ch, len(B))]
st.sort()
ind += [st[i] % 200002 for i in range(m - 2 * k + ch)]
print(' '.join((str(x) for x in ind)))


(n, k) = map(int, input().split())
tab = [tuple(map(int, input().split())) for _ in range(n)]
both = [tabi[0] for tabi in tab if tabi[1:] == (1, 1)]
both.sort()
alice = [tabi[0] for tabi in tab if tabi[1:] == (1, 0)]
bob = [tabi[0] for tabi in tab if tabi[1:] == (0, 1)]
alice.sort()
bob.sort()
ab = [alice[i] + bob[i] for i in range(min(len(alice), len(bob)))]
both += ab
both.sort()
if len(both) < k:
	print(-1)
else:
	print(sum(both[:k]))


import math, sys, bisect, heapq
from collections import defaultdict, Counter, deque
from itertools import groupby, accumulate
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda : map(int, input().split())
alele = lambda : list(map(int, input().split()))

def Y(c):
	print(['NO', 'YES'][c])

def y(c):
	print(['no', 'yes'][c])

def Yy(c):
	print(['No', 'Yes'][c])
(n, k) = ilele()
a = []
b = []
d = []
for i in range(n):
	(t, x, y) = ilele()
	if x == y == 1:
		d.append(t)
	elif x == 1:
		a.append(t)
	elif y == 1:
		b.append(t)
a.sort()
b.sort()
for (i, j) in zip(a, b):
	d.append(i + j)
print(-1) if len(d) < k else print(sum(sorted(d)[:k]))


from sys import stdin
import math
A = list(map(int, stdin.readline().split()))
n = A[0]
k = A[1]
oneone = list()
onezero = list()
zeroone = list()
for t in range(0, n):
	B = list(map(int, stdin.readline().split()))
	if B[1] == 1 and B[2] == 1:
		oneone.append(B[0])
	elif B[1] == 1 and B[2] == 0:
		onezero.append(B[0])
	elif B[1] == 0 and B[2] == 1:
		zeroone.append(B[0])
zeroone.sort()
onezero.sort()
ans = 0
DD = list()
for K in range(0, min(len(zeroone), len(onezero))):
	DD.append(zeroone[K] + onezero[K])
oneone = oneone + DD
oneone.sort()
QQ = 0
if len(oneone) < k:
	print(-1)
	QQ = 1
else:
	for t in range(0, k):
		ans += oneone[t]
if QQ == 0:
	print(ans)


(n, m) = map(int, input().split())
one = []
two = []
both = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1 and b == 0:
		one.append(t)
	elif a == 0 and b == 1:
		two.append(t)
one.sort()
two.sort()
both.sort()
if len(one) + len(both) < m:
	print(-1)
	exit()
elif len(two) + len(both) < m:
	print(-1)
	exit()
ans = 0
i = j = k = aa = bb = s = 0
while s < m:
	if i == len(one) or j == len(two):
		ans += both[k]
		k += 1
	elif k == len(both):
		ans += one[i] + two[j]
		i += 1
		j += 1
	elif one[i] + two[j] <= both[k]:
		ans += one[i] + two[j]
		i += 1
		j += 1
	else:
		ans += both[k]
		k += 1
	s += 1
print(ans)


(n, k) = [int(i) for i in input().split()]
l = []
for i in range(n):
	x = [int(i) for i in input().split()]
	l.append(x)
l.sort(key=lambda x: x[0])
from heapq import heappop, heappush
a = []
b = []
ans = 0
ak = 0
bk = 0
i = 0
while i < n and (ak < k or bk < k):
	ans += l[i][0]
	if l[i][1] == l[i][2] == 1:
		ak += 1
		bk += 1
	elif l[i][1] == 1:
		ak += 1
		heappush(a, -1 * l[i][0])
	elif l[i][2] == 1:
		bk += 1
		heappush(b, -1 * l[i][0])
	else:
		ans -= l[i][0]
	i += 1
if ak > k:
	while ak > k and a:
		ans += heappop(a)
		ak -= 1
if bk > k:
	while bk > k and b:
		ans += heappop(b)
		bk -= 1
if i == n and (ak < k or bk < k):
	print(-1)
elif i == n or not (a or b):
	print(ans)
else:
	while i < n and (a and b):
		if l[i][1] == l[i][2] == 1:
			x = -1 * heappop(a)
			y = -1 * heappop(b)
			if x + y >= l[i][0]:
				ans -= x + y - l[i][0]
			else:
				break
		i += 1
	print(ans)
	i += 1


(n, k) = map(int, input().split())
combine = []
alice = []
bob = []
ha = 0
haa = 0
for i in range(n):
	a = list(map(int, input().strip().split()))
	if a[1] == 1 and a[2] == 0:
		alice.append(a[0])
		ha += 1
	elif a[1] == 0 and a[2] == 1:
		bob.append(a[0])
		haa += 1
	elif a[1] == 1 and a[2] == 1:
		combine.append(a[0])
		ha += 1
		haa += 1
if ha < k or haa < k:
	print(-1)
else:
	bob.sort()
	alice.sort()
	combine.sort()
	sum = []
	ans = 0
	mini = min(len(alice), len(bob))
	for i in range(mini):
		sum.append(bob[i] + alice[i])
	for i in combine:
		sum.append(i)
	sum.sort()
	for i in range(k):
		ans += sum[i]
	print(ans)


(n, k) = map(int, input().split())
a = []
b = []
c = []
for i in range(n):
	(q, w, e) = map(int, input().split())
	if w and e:
		a.append(q)
	elif w:
		b.append(q)
	elif e:
		c.append(q)
if len(a) + len(b) < k or len(a) + len(c) < k:
	print(-1)
else:
	a.sort()
	b.sort()
	c.sort()
	w = 0
	t = 0
	o = 0
	p = 0
	while w < k:
		if len(b) > o and len(c) > o and (p == len(a) or c[o] + b[o] < a[p]):
			t = t + c[o] + b[o]
			o = o + 1
		else:
			t = t + a[p]
			p = p + 1
		w = w + 1
	print(t)


import io
import os

class SortedListWithSum:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._sum = sum(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._mins = [_list[0] for _list in _lists]
		self._list_lens = [len(_list) for _list in _lists]
		self._fen_tree = []
		self._list_sums = [sum(_list) for _list in _lists]
		self._fen_tree_sum = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._fen_tree_sum[:] = self._list_sums
		_fen_tree_sum = self._fen_tree_sum
		for i in range(len(_fen_tree_sum)):
			if i | i + 1 < len(_fen_tree_sum):
				_fen_tree_sum[i | i + 1] += _fen_tree_sum[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_update_sum(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree_sum
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_query_sum(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree_sum
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		_list_sums = self._list_sums
		value = _lists[pos][idx]
		self._len -= 1
		self._sum -= value
		self._fen_update(pos, -1)
		self._fen_update_sum(pos, -value)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		_list_sums[pos] -= value
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _list_sums[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		_list_sums = self._list_sums
		self._len += 1
		self._sum += value
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			self._fen_update_sum(pos, value)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_list_sums[pos] += value
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				back = _list[_load:]
				old_len = _list_lens[pos]
				old_sum = _list_sums[pos]
				new_len_front = _load
				new_len_back = old_len - new_len_front
				new_sum_back = sum(back)
				new_sum_front = old_sum - new_sum_back
				_lists.insert(pos + 1, back)
				_list_lens.insert(pos + 1, new_len_back)
				_list_sums.insert(pos + 1, new_sum_back)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = new_len_front
				_list_sums[pos] = new_sum_front
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			_list_sums.append(value)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))

	def query(self, i, j):
		if i == j:
			return 0
		(pos1, idx1) = self._fen_findkth(self._len + i if i < 0 else i)
		(pos2, idx2) = self._fen_findkth(self._len + j if j < 0 else j)
		return sum(self._lists[pos1][idx1:]) + (self._fen_query_sum(pos2) - self._fen_query_sum(pos1 + 1)) + sum(self._lists[pos2][:idx2])

	def sum(self):
		return self._sum

def solve(N, M, K, books):
	A = []
	B = []
	common = []
	padding = SortedListWithSum()
	for (i, (t, a, b)) in enumerate(books):
		if a and b:
			common.append(t)
		elif a:
			A.append(t)
		elif b:
			B.append(t)
		else:
			padding.add(t)
	A.sort()
	B.sort()
	common.sort()
	prefA = [0]
	for t in A:
		prefA.append(prefA[-1] + t)
	prefB = [0]
	for t in B:
		prefB.append(prefB[-1] + t)
	prefC = [0]
	for t in common:
		prefC.append(prefC[-1] + t)
	cMin = max(0, K - len(A), K - len(B), 2 * K - M)
	cMax = min(K, len(common))
	if cMin > cMax:
		return -1
	for i in range(cMin, len(common)):
		padding.add(common[i])
	for i in range(K - cMin, len(A)):
		padding.add(A[i])
	for i in range(K - cMin, len(B)):
		padding.add(B[i])
	best = (float('inf'),)
	for c in range(cMin, cMax + 1):
		assert 0 <= c <= len(common)
		assert 0 <= K - c <= len(A)
		assert 0 <= K - c <= len(B)
		pad = M - c - (K - c) * 2
		assert 0 <= pad <= N
		cost = prefC[c] + prefB[K - c] + prefA[K - c] + padding.query(0, min(pad, len(padding)))
		best = min(best, (cost, c))
		if 0 <= K - c - 1 < len(A):
			x = A[K - c - 1]
			padding.add(x)
		if 0 <= K - c - 1 < len(B):
			x = B[K - c - 1]
			padding.add(x)
		if c < len(common):
			x = common[c]
			padding.remove(x)
	assert best[0] != float('inf')
	needC = best[1]
	needA = K - needC
	needB = K - needC
	needPad = M - needC - needB - needA
	check = 0
	ans = []
	for (i, (t, a, b)) in sorted(enumerate(books), key=lambda ix: ix[1][0]):
		if a and b:
			if needC:
				needC -= 1
				ans.append(str(i + 1))
				check += t
				continue
		if a:
			if needA:
				needA -= 1
				ans.append(str(i + 1))
				check += t
				continue
		if b:
			if needB:
				needB -= 1
				ans.append(str(i + 1))
				check += t
				continue
		if needPad:
			needPad -= 1
			ans.append(str(i + 1))
			check += t
	assert len(ans) == M
	assert check == best[0]
	return str(best[0]) + '\n' + ' '.join((x for x in ans))
if False:
	import random
	random.seed(0)
	N = 2 * 10 ** 2
	for i in range(1000):
		books = [[random.randint(1, 20), random.randint(0, 1), random.randint(0, 1)] for i in range(N)]
		M = min(N, random.randint(1, 100))
		K = min(M, random.randint(1, 100))
		solve(N, M, K, books)
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N, M, K) = [int(x) for x in input().split()]
books = [[int(x) for x in input().split()] for i in range(N)]
ans = solve(N, M, K, books)
print(ans)


import sys

class E1ReadingBooksEasyVersion:

	def solve(self, tc=0):
		(n, k) = [int(_) for _ in input().split()]
		books = []
		for i in range(n):
			books.append([int(_) for _ in input().split()])
		a = []
		b = []
		both = []
		for i in range(n):
			book = books[i]
			if book[1] and book[2]:
				both.append(book[0])
			elif book[1]:
				a.append(book[0])
			elif book[2]:
				b.append(book[0])
		a.sort()
		b.sort()
		both.sort()
		prea = [0] * (len(a) + 1)
		for i in range(1, len(a) + 1):
			prea[i] = prea[i - 1] + a[i - 1]
		preb = [0] * (len(b) + 1)
		for i in range(1, len(b) + 1):
			preb[i] = preb[i - 1] + b[i - 1]
		preboth = [0] * (len(both) + 1)
		for i in range(1, len(both) + 1):
			preboth[i] = preboth[i - 1] + both[i - 1]
		ans = float('inf')
		for i in range(len(both) + 1):
			if i > k:
				break
			if len(a) >= k - i and len(b) >= k - i:
				ans = min(ans, preboth[i] + prea[k - i] + preb[k - i])
		print(ans if ans != float('inf') else -1)
solver = E1ReadingBooksEasyVersion()
input = sys.stdin.readline
solver.solve()


from sys import stdin
import math
[n, k] = [int(j) for j in stdin.readline().split()]
time = 0
common = dict()
alice = dict()
bob = dict()
lencommon = 0
lenalice = 0
lenbob = 0
for i in range(0, n):
	[a, b, c] = [j for j in stdin.readline().split()]
	a = int(a)
	if b == '1' and c == '1':
		lencommon += 1
		if a in common.keys():
			common[a] += 1
		else:
			common[a] = 1
	elif b == '1':
		lenalice += 1
		if a in alice.keys():
			alice[a] += 1
		else:
			alice[a] = 1
	elif c == '1':
		lenbob += 1
		if a in bob.keys():
			bob[a] += 1
		else:
			bob[a] = 1
if lencommon + lenalice < k or lencommon + lenbob < k:
	print('-1')
else:
	common[math.inf] = 1
	alice[math.inf] = 1
	bob[math.inf] = 1
	A = min(alice)
	B = min(bob)
	C = min(common)
	for i in range(0, k):
		if A + B < C:
			time += A + B
			alice[A] -= 1
			bob[B] -= 1
			if alice[A] == 0:
				del alice[A]
				A = min(alice)
			if bob[B] == 0:
				del bob[B]
				B = min(bob)
		else:
			time += C
			common[C] -= 1
			if common[C] == 0:
				del common[C]
				C = min(common)
	print(time)


import io, os, math

def ri():
	return int(input().strip())

def rl():
	return list(map(int, input().strip().split()))

def Solve():
	(n, k) = rl()
	(al, ar) = ([], [])
	p = []
	for i in range(n):
		(t, a, b) = rl()
		if a == 1 and b == 1:
			p.append(t)
		if a == 1 and b == 0:
			al.append(t)
		if a == 0 and b == 1:
			ar.append(t)
	al.sort()
	ar.sort()
	for i in range(min(len(al), len(ar))):
		p.append(al[i] + ar[i])
	p.sort()
	if len(p) < k:
		print(-1)
	else:
		print(sum(p[:k]))
T = 1
while T:
	T -= 1
	Solve()


import bisect

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
l = inlt()
n = l[0]
k = l[1]
alice = []
bob = []
good = []
for i in range(n):
	l = inlt()
	if l[1] == 1 and l[2] == 1:
		good.append(l)
	elif l[1] == 1:
		alice.append(l)
	elif l[2] == 1:
		bob.append(l)
good.sort(key=lambda j: j[0])
alice.sort(key=lambda j: j[0])
bob.sort(key=lambda j: j[0])
a = 0
b = 0
g = 0
total = 0
book = 0
while book < k:
	if g < len(good):
		if a >= len(alice) or b >= len(bob):
			total += good[g][0]
			g += 1
		elif alice[a][0] + bob[b][0] < good[g][0]:
			total += alice[a][0] + bob[b][0]
			a += 1
			b += 1
		else:
			total += good[g][0]
			g += 1
	elif a < len(alice) and b < len(bob):
		total += alice[a][0] + bob[b][0]
		a += 1
		b += 1
	else:
		total = -1
		break
	book += 1
print(total)


import os
import sys
from io import BytesIO, IOBase
from bisect import bisect_left, bisect_right
import threading
from collections import Counter, defaultdict
arr = []

def main():
	for _ in range(1):
		(n, k) = map(int, input().split())
		ar3 = []
		ar1 = []
		ar2 = []
		for i in range(n):
			(a, b, c) = map(int, input().split())
			if b == c == 1:
				ar3.append(a)
			else:
				if b == 1:
					ar1.append(a)
				if c == 1:
					ar2.append(a)
		t = 2 * max(0, k - len(ar3)) + len(ar3)
		if len(ar3) + len(ar1) < k or len(ar3) + len(ar2) < k:
			print(-1)
		else:
			ar3.sort()
			ar1.sort()
			ar2.sort()
			pt1 = pt2 = 0
			i1 = 0
			i2 = 0
			i3 = 0
			ans = 0
			m_ = 0
			while i1 < len(ar1) and i2 < len(ar2) and (i3 < len(ar3)):
				if ar1[i1] + ar2[i2] < ar3[i3]:
					ans = ans + ar1[i1] + ar2[i2]
					i1 += 1
					i2 += 1
				else:
					ans = ans + ar3[i3]
					i3 += 1
				pt1 += 1
				pt2 += 1
				if pt1 == pt2 == k:
					break
			if i2 >= len(ar2):
				(i1, i2) = (i2, i1)
				(ar1, ar2) = (ar2, ar1)
			while pt1 < k:
				if i1 < len(ar1) and i3 < len(ar3) and (ar3[i3] < ar1[i1]):
					ans += ar3[i3]
					i3 += 1
					pt2 += 1
				elif i1 < len(ar1):
					ans += ar1[i1]
					i1 += 1
				else:
					ans += ar3[i3]
					i3 += 1
					pt2 += 1
				pt1 += 1
			while pt2 < k:
				if i1 < len(ar1) and i3 < len(ar3) and (ar3[i3] < ar1[i1]):
					ans += ar3[i3]
					i3 += 1
				elif i2 < len(ar2):
					ans += ar2[i2]
					i2 += 1
				else:
					ans += ar3[i3]
					i3 += 1
				pt2 += 1
			print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


(n, k) = map(int, input().split())
both = list()
alice = list()
bob = list()
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a and b:
		both.append(t)
	elif a:
		alice.append(t)
	elif b:
		bob.append(t)
both.sort(reverse=True)
alice.sort(reverse=True)
bob.sort(reverse=True)
al = k
bb = k
ans = 0
while True:
	if al <= 0 or bb <= 0:
		break
	if not len(alice) and al > 0:
		if not len(both):
			break
	if not len(bob) and bb > 0:
		if not len(both):
			break
	if len(both) and len(alice) and len(bob):
		if both[-1] < alice[-1] + bob[-1]:
			ans += both[-1]
			both.pop()
		else:
			ans += alice[-1] + bob[-1]
			alice.pop()
			bob.pop()
		al -= 1
		bb -= 1
	elif len(alice) and len(bob):
		if len(alice):
			al -= 1
			ans += alice.pop()
		if len(bob):
			bb -= 1
			ans += bob.pop()
	elif len(both):
		ans += both.pop()
		al -= 1
		bb -= 1
if al <= 0 and bb <= 0:
	print(ans)
else:
	print('-1')


(n, k) = map(int, input().split())
books = []
booksA = []
booksB = []
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 0:
		booksA.append(t)
	elif a == 0 and b == 1:
		booksB.append(t)
	elif a == 1 and b == 1:
		books.append(t)
booksA.sort(reverse=True)
booksB.sort(reverse=True)
books.sort(reverse=True)
t = 0
for _ in range(k):
	if not books:
		if not booksA or not booksB:
			t = -1
			break
		else:
			t += booksA.pop() + booksB.pop()
	elif (not booksA or not booksB) or books[-1] < booksA[-1] + booksB[-1]:
		t += books.pop()
	else:
		t += booksA.pop() + booksB.pop()
print(t)


import sys
import math as mt
input = sys.stdin.buffer.readline
t = 1

def Sort(sub_li):
	sub_li.sort(key=lambda x: x[0])
	return sub_li
for _ in range(t):
	(n, k) = map(int, input().split())
	l2 = []
	common = []
	alice = []
	bob = []
	for ___ in range(n):
		(time, a, b) = map(int, input().split())
		if a & b:
			common.append(time)
		else:
			if a:
				alice.append(time)
			if b:
				bob.append(time)
	common.sort()
	alice.sort()
	bob.sort()
	if len(common) + min(len(alice), len(bob)) < k:
		print(-1)
	else:
		common.append(10 ** 9)
		alice.append(10 ** 9)
		bob.append(10 ** 9)
		(al, bo) = (0, 0)
		co = 0
		i = 0
		ans = 0
		while i < k:
			if common[co] <= bob[bo] + alice[al]:
				ans += common[co]
				i += 1
				co += 1
			else:
				ans += bob[bo] + alice[al]
				i += 1
				al += 1
				bo += 1
		print(ans)


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
books = [tuple(map(int, input().split())) for _ in range(n)]
books.sort(key=lambda x: (x[0], -x[1], -x[2]))
ans = 0
comm = []
cnt_a = []
cnt_b = []
for (t, a, b) in books:
	if a == 0 and b == 0:
		pass
	elif a == 1 and b == 1:
		if len(cnt_a) + len(comm) < k or len(cnt_b) + len(comm) < k:
			comm.append(t)
		elif cnt_a and cnt_b and (cnt_a[-1] + cnt_b[-1] > t):
			cnt_a.pop()
			cnt_b.pop()
			comm.append(t)
	elif a == 1 and len(cnt_a) + len(comm) < k:
		cnt_a.append(t)
	elif b == 1 and len(cnt_b) + len(comm) < k:
		cnt_b.append(t)
	else:
		pass
while cnt_a and len(cnt_a) + len(comm) > k:
	cnt_a.pop()
while cnt_b and len(cnt_b) + len(comm) > k:
	cnt_b.pop()
if len(cnt_a) + len(comm) < k or len(cnt_b) + len(comm) < k:
	print(-1)
else:
	print(sum(cnt_a) + sum(cnt_b) + sum(comm))


(n, k) = map(int, input().split())
t11 = []
t01 = []
t10 = []
for j in range(n):
	(ti, ai, bi) = map(int, input().split())
	if ai == 0 and bi == 0:
		continue
	elif ai == 1 and bi == 1:
		t11.append(ti)
	elif ai == 0 and bi == 1:
		t01.append(ti)
	else:
		t10.append(ti)
lt11 = len(t11)
lt10 = len(t10)
lt01 = len(t01)
if lt11 + min(lt10, lt01) >= k:
	t01 = sorted(t01)
	t10 = sorted(t10)
	t1 = t0 = tot = 0
	for i in range(min(lt10, lt01)):
		t11.append(t10[i] + t01[i])
	print(sum(sorted(t11)[:k]))
else:
	print('-1')


(n, k) = map(int, input().split())
p1 = []
a1 = []
b1 = []
c1 = 0
c2 = 0
for _ in range(n):
	(p, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		p1.append(p)
		c1 += 1
		c2 += 1
	elif a == 1:
		a1.append(p)
		c1 += 1
	elif b == 1:
		b1.append(p)
		c2 += 1
if c1 < k or c2 < k:
	print(-1)
else:
	a1.sort()
	b1.sort()
	i = 0
	while i < len(a1) and i < len(b1):
		p1.append(a1[i] + b1[i])
		i += 1
	p1.sort()
	ans = 0
	for i in range(k):
		ans += p1[i]
	print(ans)


import sys
input = lambda : sys.stdin.readline().rstrip()
from heapq import heapify, heappop, heappush
(n, k) = map(int, input().split())
(a, b, c) = ([], [], [])
for _ in range(n):
	(t, e, d) = map(int, input().split())
	if e and d:
		a.append(t)
	elif e:
		b.append(t)
	elif d:
		c.append(t)
fl = False
if len(b) + len(a) >= k and len(c) + len(a) >= k:
	fl = True
if not fl:
	print(-1)
	sys.exit(0)
heapify(a)
b.sort()
c.sort()
ans = 0
for i in range(min(len(b), len(c))):
	heappush(a, b[i] + c[i])
while k:
	ans += heappop(a)
	k -= 1
print(ans)


import sys, math, cmath, time
start_time = time.time()

def solve():
	(n, k) = invr()
	q = []
	w = []
	qw = []
	for i in range(n):
		(t, a, b) = invr()
		if a & b > 0:
			qw.append(t)
		elif a > 0:
			q.append(t)
		elif b > 0:
			w.append(t)
	q.sort()
	w.sort()
	for i in range(min(len(q), len(w))):
		qw.append(q[i] + w[i])
	if len(qw) < k:
		print(-1)
	else:
		print(sum(sorted(qw)[:k]))

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	for tt in range(t):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
		sys.stdout.close()

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	return input().strip()

def invr():
	return map(int, input().split())

def counter(a):
	q = dict()
	for i in range(len(a)):
		if a[i] not in q:
			q[a[i]] = 0
		q[a[i]] = q[a[i]] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = (q[ord(a[i]) - 97], 1)
	return q

def factors(n):
	q = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			q.append(i)
			q.append(n // i)
	return list(sorted(list(set(q))))

def prime_factors(n):
	q = []
	while n % 2 == 0:
		q.append(2)
		n = n // 2
	for i in range(3, int(n ** 0.5) + 1, 2):
		while n % i == 0:
			q.append(i)
			n = n // i
	if n > 2:
		q.append(n)
	return list(sorted(q))
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from math import sqrt, floor, factorial, gcd, log
from collections import deque, Counter, defaultdict
from itertools import permutations, combinations
from math import gcd
from bisect import bisect
input = lambda : sys.stdin.readline().rstrip('\r\n')
read = lambda : list(map(int, input().strip().split(' ')))

def solve():
	(n, k_) = read()
	both = []
	a = []
	b = []
	for _ in range(n):
		arr = read()
		(x, y, z) = arr
		if y & z:
			both.append(arr)
		elif y:
			a.append(arr)
		elif z:
			b.append(arr)
	both.sort()
	a.sort()
	b.sort()
	t = 0
	books = 0
	(i, j, k) = (0, 0, 0)
	while books < k_ and i < len(both) and (j < len(a)) and (k < len(b)):
		if both[i][0] <= a[j][0] + b[k][0]:
			t += both[i][0]
			books += 1
			i += 1
		else:
			t += a[j][0] + b[k][0]
			j += 1
			k += 1
			books += 1
	while books < k_ and j < len(a) and (k < len(b)):
		t += a[j][0] + b[k][0]
		j += 1
		k += 1
		books += 1
	while books < k_ and i < len(both):
		t += both[i][0]
		books += 1
		i += 1
	if books < k_:
		print(-1)
	elif books == k_:
		print(t)
solve()


import sys
input = sys.stdin.readline

def solve(n, k, t, a, b):
	alice_only = []
	bob_only = []
	both = []
	for i in range(n):
		if a[i] and b[i]:
			both.append(t[i])
		elif a[i] and (not b[i]):
			alice_only.append(t[i])
		elif b[i] and (not a[i]):
			bob_only.append(t[i])
	if len(bob_only) + len(both) < k:
		return -1
	elif len(alice_only) + len(both) < k:
		return -1
	bob_only.sort()
	alice_only.sort()
	both.sort()
	both_pre = [0]
	bob_pre = [0]
	alice_pre = [0]
	for tb in bob_only:
		bob_pre.append(bob_pre[-1] + tb)
	for ta in alice_only:
		alice_pre.append(alice_pre[-1] + ta)
	for tbth in both:
		both_pre.append(both_pre[-1] + tbth)
	best = float('inf')
	lb1 = k - len(alice_only)
	lb2 = k - len(bob_only)
	for cur_k in range(max(lb1, lb2, 0), min(len(both_pre), k + 1)):
		time_both = both_pre[cur_k]
		time_alice = alice_pre[k - cur_k]
		time_bob = bob_pre[k - cur_k]
		best = min(best, time_both + time_alice + time_bob)
	if len(alice_pre) > k and len(bob_pre) > k:
		best = min(best, alice_pre[k] + bob_pre[k])
	return best
(n, k) = map(int, input().split())
(t, a, b) = ([], [], [])
for _ in range(n):
	(ti, ai, bi) = map(int, input().split())
	t.append(ti)
	a.append(ai)
	b.append(bi)
print(solve(n, k, t, a, b))


temparr = input()
temparr = temparr.split()
n = int(temparr[0])
minimum = int(temparr[1])
common = []
alice = []
bob = []
for i in range(n):
	temparr = input()
	temparr = temparr.split()
	t = int(temparr[0])
	a = int(temparr[1])
	b = int(temparr[2])
	if a == 1 and b == 1:
		common.append(t)
		continue
	if a == 1:
		alice.append(t)
	if b == 1:
		bob.append(t)
common = sorted(common)
alice = sorted(alice)
bob = sorted(bob)
counta = 0
countb = 0
commonlen = len(common)
alicelen = len(alice)
boblen = len(bob)
i = 0
j = 0
k = 0
flag = 0
ans = 0
if commonlen + alicelen < minimum or commonlen + boblen < minimum:
	print(-1)
else:
	while True:
		if counta >= minimum and countb >= minimum:
			print(ans)
			break
		if i == commonlen and j == alicelen and (k == boblen):
			flag = 1
			break
		if j == alicelen or k == boblen:
			ans += common[i]
			countb += 1
			counta += 1
			i += 1
		elif i == commonlen:
			counta += 1
			countb += 1
			ans += alice[j]
			ans += bob[k]
			j += 1
			k += 1
		elif common[i] <= alice[j] + bob[k]:
			ans += common[i]
			i += 1
			counta += 1
			countb += 1
		else:
			counta += 1
			countb += 1
			ans += alice[j]
			ans += bob[k]
			j += 1
			k += 1
	if flag == 1:
		print(-1)


from sys import stdin, stdout
import bisect

def st():
	return list(stdin.readline())

def inp():
	return int(stdin.readline())

def li():
	return list(map(int, stdin.readline().split()))

def mp():
	return map(int, stdin.readline().split())

def pr(n):
	stdout.write(str(n) + '\n')

def soe(limit):
	l = [1] * (limit + 1)
	prime = []
	for i in range(2, limit + 1):
		if l[i]:
			for j in range(i * i, limit + 1, i):
				l[j] = 0
	for i in range(2, limit + 1):
		if l[i]:
			prime.append(i)
	return prime

def segsoe(low, high):
	limit = int(high ** 0.5) + 1
	prime = soe(limit)
	n = high - low + 1
	l = [0] * (n + 1)
	for i in range(len(prime)):
		lowlimit = low // prime[i] * prime[i]
		if lowlimit < low:
			lowlimit += prime[i]
		if lowlimit == prime[i]:
			lowlimit += prime[i]
		for j in range(lowlimit, high + 1, prime[i]):
			l[j - low] = 1
	for i in range(low, high + 1):
		if not l[i - low]:
			if i != 1:
				print(i)

def power(a, n):
	r = 1
	while n:
		if n & 1:
			r = r * a
			n = n - 1
		else:
			a = a * a
			n = n >> 1
	return r

def solve():
	(n, k) = mp()
	both = []
	first = []
	second = []
	for i in range(n):
		(a, b, c) = mp()
		if b == 1 and c == 1:
			both.append(a)
		elif b == 1 and c == 0:
			first.append(a)
		elif b == 0 and c == 1:
			second.append(a)
	if len(both) + len(first) < k or len(both) + len(second) < k:
		pr(-1)
	else:
		both.sort()
		first.sort()
		second.sort()
		(i, j, z) = (0, 0, 0)
		p = 0
		while k != 0:
			if z < len(both):
				temp = both[z]
			else:
				temp = float('inf')
			if i < len(first):
				temp1 = first[i]
			else:
				temp1 = float('inf')
			if j < len(second):
				temp2 = second[j]
			else:
				temp2 = float('inf')
			if temp <= temp1 + temp2:
				p += temp
				z += 1
			else:
				p += temp1 + temp2
				i += 1
				j += 1
			k -= 1
		print(p)
solve()


import sys
input = sys.stdin.readline

def main():
	(n, k) = map(int, input().split())
	a = []
	b = []
	whole = []
	for _ in range(n):
		(t, x, y) = map(int, input().split())
		if x + y == 2:
			whole.append(t)
		elif x + y == 1:
			if x:
				a.append(t)
			else:
				b.append(t)
	a.sort()
	b.sort()
	for (x, y) in zip(a, b):
		whole.append(x + y)
	whole.sort()
	if len(whole) < k:
		print('-1')
	else:
		print(sum(whole[:k]))
main()


(n, k) = map(int, input().split())
books = []
alice = []
bobs = []
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		books.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bobs.append(t)
books = sorted(books)
alice = sorted(alice)
bobs = sorted(bobs)
b = 0
ab = 0
count = 0
ans = 0
while count < k and (b < len(books) and (ab < len(alice) and ab < len(bobs))):
	if books[b] <= alice[ab] + bobs[ab]:
		ans += books[b]
		b += 1
	else:
		ans += alice[ab] + bobs[ab]
		ab += 1
	count += 1
if count == k:
	print(ans)
else:
	while count < k and b < len(books):
		ans += books[b]
		b += 1
		count += 1
	while count < k and (ab < len(alice) and ab < len(bobs)):
		ans += alice[ab] + bobs[ab]
		ab += 1
		count += 1
	if count < k:
		print(-1)
	else:
		print(ans)


(n, k) = list(map(int, input().rstrip().split()))
t = []
ta = []
tb = []
common = 0
cm = {}
for i in range(n):
	a = list(map(int, input().rstrip().split()))
	if a[1] == 1 & a[2] == 1:
		t.append(a[0])
	else:
		if a[1] == 1:
			ta.append(a[0])
		if a[2] == 1:
			tb.append(a[0])
if len(ta) < k - len(t) or len(tb) < k - len(t):
	print(-1)
else:
	ta.sort()
	tb.sort()
	t.sort()
	s = []
	for i in range(min(len(ta), len(tb))):
		s.append(ta[i] + tb[i])
	l = t[:k] + s[:k]
	l.sort()
	print(sum(l[:k]))


from sys import stdin, stdout, setrecursionlimit
(n, k) = map(int, stdin.readline().split())
a = []
b = []
ab = []
for _ in range(n):
	(x, y, z) = map(int, stdin.readline().split())
	if y == 1 and z == 1:
		ab.append(x)
	if y == 1 and z == 0:
		a.append(x)
	if y == 0 and z == 1:
		b.append(x)
a.sort()
b.sort()
ab.sort()
if len(ab) + min(len(a), len(b)) < k:
	print(-1)
else:
	p = 0
	e = 0
	ans = 0
	for i in range(k):
		if p == min(len(a), len(b)):
			for j in range(k - i):
				ans += ab[e]
				e += 1
			break
		elif e == len(ab):
			for r in range(k - i):
				ans += a[p] + b[p]
				p += 1
			break
		ans += min(a[p] + b[p], ab[e])
		if a[p] + b[p] < ab[e]:
			p += 1
		else:
			e += 1
	print(ans)


import math
from collections import Counter, deque
L = lambda : list(map(int, input().split()))
M = lambda : map(int, input().split())
I = lambda : int(input())
IN = lambda : input()
mod = 10 ** 9 + 7

def s(a):
	print(' '.join(list(map(str, a))))

def solve():
	(n, k) = M()
	a = []
	b = []
	d = []
	for i in range(n):
		(t, x, y) = M()
		if x + y == 2:
			d.append(t)
		elif x == 1:
			a.append(t)
		elif y == 1:
			b.append(t)
	a.sort()
	b.sort()
	for i in range(min(len(a), len(b))):
		d.append(a[i] + b[i])
	if len(d) < k:
		print(-1)
	else:
		d.sort()
		print(sum(d[:k]))
for i in range(1):
	solve()


import sys
input = sys.stdin.readline
(n, k) = list(map(int, input().split()))
c = []
d = []
e = []
for i in range(n):
	(t, a, b) = list(map(int, input().split()))
	if a == 1 and b == 1:
		c.append(t)
	if a == 0 and b == 1:
		d.append(t)
	if a == 1 and b == 0:
		e.append(t)
d.sort()
e.sort()
x = min(len(d), len(e))
for i in range(x):
	c.append(d[i] + e[i])
c.sort()
if len(c) < k:
	print(-1)
else:
	print(sum(c[:k]))


(n, k) = list(map(int, input().split()))
books = [[], [], [], []]
for i in range(n):
	s = list(map(int, input().split()))
	if s[1] == 1 and s[2] == 1:
		books[2].append(s[0])
	elif s[2] == 1:
		books[1].append(s[0])
	elif s[1] == 1:
		books[0].append(s[0])
if len(books[0]) + len(books[2]) < k or len(books[1]) + len(books[2]) < k:
	print(-1)
else:
	for x in books:
		x.sort()
	t = 0
	al = 0
	bl = 0
	fi = 0
	si = 0
	can = True
	while al < k or bl < k:
		if fi < len(books[0]) and fi < len(books[1]) and (si < len(books[2])):
			c1 = books[0][fi] + books[1][fi]
			c2 = books[2][si]
			if c1 < c2:
				al += 1
				bl += 1
				t = t + c1
				fi = fi + 1
			else:
				al += 1
				bl += 1
				t = t + c2
				si = si + 1
		elif fi == len(books[0]):
			needed = k - al
			t = t + sum(books[2][si:si + needed])
			break
		elif fi == len(books[1]):
			needed = k - bl
			t = t + sum(books[2][si:si + needed])
			break
		elif si == len(books[2]):
			needed = k - al
			t = t + sum(books[0][fi:fi + needed])
			needed = k - bl
			t = t + sum(books[1][fi:fi + needed])
			break
		else:
			can = False
			break
	if can:
		print(t)
	else:
		print(-1)


(n, k) = map(int, input().split())
a = []
b = []
ab = []
c = 0
p = 0
e = 0
for q in range(n):
	(x, y, z) = map(int, input().split())
	if y == 1 and z == 0:
		a.append(x)
	elif y == 0 and z == 1:
		b.append(x)
	elif y == 1 and z == 1:
		ab.append(x)
a.sort()
b.sort()
ab.sort()
if len(ab) + min(len(a), len(b)) < k:
	print('-1')
else:
	for h in range(k):
		if p == min(len(a), len(b)):
			c = c + sum(ab[e:e + k - h])
			break
		elif e == len(ab):
			c = c + sum(a[p:p + k - h]) + sum(b[p:p + k - h])
			break
		c = c + min(a[p] + b[p], ab[e])
		if a[p] + b[p] < ab[e]:
			p = p + 1
		else:
			e = e + 1
	print(c)


(n, k) = [int(i) for i in input().split()]
arr = []
for i in range(n):
	arr.append([int(i) for i in input().split()])
one_one = []
zero_one = []
one_zero = []
for i in arr:
	if i[2] == i[1] == 1:
		one_one.append(i[0])
	elif i[1] == 1:
		one_zero.append(i[0])
	elif i[2] == 1:
		zero_one.append(i[0])
one_one.append(10 ** 20)
one_zero.append(10 ** 20)
zero_one.append(10 ** 20)
one_one.sort()
zero_one.sort()
one_zero.sort()
ptr1 = ptr2 = ptr3 = 0
n1 = 0
ans = 0
while n1 < k:
	if one_one[ptr1] < one_zero[ptr2] + zero_one[ptr3]:
		ans += one_one[ptr1]
		ptr1 += 1
		n1 += 1
	else:
		ans += one_zero[ptr2] + zero_one[ptr3]
		ptr2 += 1
		ptr3 += 1
		n1 += 1
	if ans >= 10 ** 20:
		ans = -1
		break
print(ans)


import sys
input = sys.stdin.readline
(inp, ip) = (lambda : int(input()), lambda : [int(w) for w in input().split()])
(n, k) = ip()
(t, a, b) = ([0] * n, [0] * n, [0] * n)
both = []
(alice, bob) = ([], [])
for i in range(n):
	(t[i], a[i], b[i]) = ip()
	if a[i] and b[i]:
		both.append(t[i])
	elif a[i]:
		alice.append(t[i])
	elif b[i]:
		bob.append(t[i])
if a.count(1) < k or b.count(1) < k:
	print(-1)
	exit()
alice.sort()
bob.sort()
m = min(len(alice), len(bob))
for i in range(m):
	both.append(alice[i] + bob[i])
both.sort()
print(sum(both[:k]))


import sys
input = sys.stdin.readline

def main():
	(n, k) = map(int, input().split())
	a_s = []
	b_s = []
	ab_s = []
	for _ in range(n):
		(t, a, b) = map(int, input().split())
		if a == b == 1:
			ab_s.append(t)
		elif a == 1:
			a_s.append(t)
		elif b == 1:
			b_s.append(t)
	la = len(a_s)
	lb = len(b_s)
	lab = len(ab_s)
	if la + lab < k or lb + lab < k:
		print(-1)
		return
	a_s.sort()
	b_s.sort()
	for i in range(min(la, lb)):
		tmp = a_s[i] + b_s[i]
		ab_s.append(tmp)
	ab_s.sort()
	print(sum(ab_s[:k]))
main()


import sys
from collections import defaultdict as dd
from collections import Counter as cc
from queue import Queue
import math
import itertools
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass
input = lambda : sys.stdin.buffer.readline().rstrip()
(q, w) = map(int, input().split())
e = []
r = []
t = []
z = 0
x = 0
for i in range(q):
	(a, b, c) = map(int, input().split())
	if b == 1 and c == 1:
		e.append(a)
		z += 1
		x += 1
	elif b == 1 and c == 0:
		r.append(a)
		x += 1
	elif b == 0 and c == 1:
		t.append(a)
		z += q
r = sorted(r)
t = sorted(t)
for i in range(min(len(r), len(t))):
	e.append(r[i] + t[i])
e = sorted(e)
i = 0
t = 0
k = 0
b = len(e)
if b < w:
	print(-1)
else:
	while i < w:
		if t < b:
			k += e[t]
			t += 1
		i += 1
	print(k)


import itertools
(n, k) = map(int, input().split())
both = [0]
alice = [0]
bob = [0]
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a and b:
		both.append(t)
	elif a:
		alice.append(t)
	elif b:
		bob.append(t)
if len(alice) + len(both) < k or len(bob) + len(both) < k:
	print(-1)
	exit()
both.sort()
alice.sort()
bob.sort()
cs_both = list(itertools.accumulate(both))
cs_alice = list(itertools.accumulate(alice))
cs_bob = list(itertools.accumulate(bob))
ans = float('inf')
for i in range(k + 1):
	try:
		tmp = cs_both[i]
	except IndexError:
		break
	if i == k:
		ans = min(ans, tmp)
	try:
		tmp += cs_alice[k - i]
	except IndexError:
		continue
	try:
		tmp += cs_bob[k - i]
	except IndexError:
		continue
	ans = min(ans, tmp)
if ans == float('inf'):
	print(-1)
else:
	print(ans)


import sys
input = sys.stdin.readline
from collections import *
(n, k) = map(int, input().split())
d = defaultdict(list)
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1 and b == 1:
		d[0].append(t)
	elif a == 1 and b == 0:
		d[1].append(t)
	elif a == 0 and b == 1:
		d[2].append(t)
acc = defaultdict(list)
for i in range(3):
	d[i].sort()
	acc[i].append(0)
	for ti in d[i]:
		acc[i].append(acc[i][-1] + ti)
ans = 10 ** 18
for i in range(min(k, len(d[0])) + 1):
	if k - i > len(d[1]) or k - i > len(d[2]):
		continue
	ans = min(ans, acc[0][i] + acc[1][k - i] + acc[2][k - i])
if ans == 10 ** 18:
	print(-1)
else:
	print(ans)


import bisect
import collections
import copy
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
from typing import *
sys.setrecursionlimit(99999)
(n, k) = map(int, input().split())
(booksa, booksb, booksc) = ([], [], [])
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == 0 and b == 1:
		booksb.append(t)
	if a == 1 and b == 0:
		booksa.append(t)
	if a == 1 and b == 1:
		booksc.append(t)
booksa.sort()
booksb.sort()
booksc.sort()
booksa = booksa[:k]
booksb = booksb[:k]
na = len(booksa)
nb = len(booksb)
s = sum(booksa) + sum(booksb)
cj = 0
while na < k or nb < k:
	if cj == len(booksc):
		break
	s += booksc[cj]
	cj += 1
	na += 1
	nb += 1
while na > k and booksa:
	s -= booksa.pop()
	na -= 1
while nb > k and booksb:
	s -= booksb.pop()
	nb -= 1
while cj < len(booksc) and (booksa or booksb) and (na >= k) and (nb >= k):
	sc = booksc[cj]
	cj += 1
	sa = 0
	sb = 0
	if booksa:
		sa = booksa.pop()
	if booksb:
		sb = booksb.pop()
	if sa + sb > sc:
		s += sc
		s -= sa
		s -= sb
	else:
		break
if na >= k and nb >= k:
	print(s)
else:
	print(-1)


it = lambda : list(map(int, input().strip().split()))

def solve():
	(n, k) = it()
	bob = []
	both = []
	alice = []
	for _ in range(n):
		(t, a, b) = it()
		if a and b:
			both.append(t)
		elif a:
			alice.append(t)
		elif b:
			bob.append(t)
	M = len(both)
	N = min(len(bob), len(alice))
	if M + N < k:
		return -1
	bob.sort()
	both.sort()
	alice.sort()
	merge = []
	for i in range(N):
		merge.append(alice[i] + bob[i])
	a = 0
	i = 0
	j = 0
	while k > 0 and (i < M or j < N):
		k -= 1
		if i >= M or (j < N and merge[j] < both[i]):
			a += merge[j]
			j += 1
		else:
			a += both[i]
			i += 1
	return a
print(solve())


(n, k) = map(int, input().split())
common_books = []
alice_books = []
bob_books = []
for i in range(n):
	(duration, alice, bob) = map(int, input().split())
	if alice and bob:
		collection = common_books
	elif alice:
		collection = alice_books
	elif bob:
		collection = bob_books
	else:
		collection = None
	if collection is not None:
		collection.append(duration)

def get0(collection, idx):
	if idx < len(collection):
		return collection[idx]
	return 0
if len(bob_books) + len(common_books) < k or len(alice_books) + len(common_books) < k:
	print(-1)
else:
	for collection in (common_books, alice_books, bob_books):
		collection.sort()
	icom = 0
	iali = 0
	ibob = 0
	ncom = len(common_books)
	nali = len(alice_books)
	nbob = len(bob_books)
	total = 0
	for i in range(k):
		if icom < ncom and get0(alice_books, iali) + get0(bob_books, ibob) >= common_books[icom]:
			total += common_books[icom]
			icom += 1
		elif iali < nali and ibob < nbob:
			total += alice_books[iali]
			total += bob_books[ibob]
			iali += 1
			ibob += 1
		else:
			total += common_books[icom]
			icom += 1
	print(total)


(n, k) = input().split()
n = int(n)
k = int(k)
both = []
al = []
bl = []
for i in range(0, n):
	(t, a, b) = input().split()
	t = int(t)
	a = int(a)
	b = int(b)
	if a == b == 1:
		both.append(t)
	elif a == 1:
		al.append(t)
	elif b == 1:
		bl.append(t)
both.sort()
al.sort()
bl.sort()
result = []
s = 0
j = 0
while j < len(both):
	i = both[j]
	if len(al) > s and len(bl) > s and (i > al[s] + bl[s]):
		result.append(al[s])
		result.append(bl[s])
		s += 1
	else:
		result.append(i)
		j += 1
	k -= 1
	if k == 0:
		break
if k > 0:
	if len(al[s:s + k]) == k and len(bl[s:s + k]) == k:
		result.extend(al[s:s + k])
		result.extend(bl[s:s + k])
		print(sum(result))
	else:
		print(-1)
else:
	print(sum(result))


from sys import stdin
(n, k) = map(int, stdin.readline().split())
a = []
b = []
both = []
for _ in range(n):
	(t, x, y) = map(int, stdin.readline().split())
	if x == 1 and y == 1:
		both.append(t)
	elif x == 1:
		a.append(t)
	elif y == 1:
		b.append(t)
a.sort()
b.sort()
both.sort()
if len(both) + len(a) < k or len(both) + len(b) < k:
	print(-1)
else:
	li = i = j = ti = 0
	while li != k:
		if i == min(len(a), len(b)):
			ti += both[j]
			j += 1
		elif j == len(both):
			ti += a[i] + b[i]
			i += 1
		elif a[i] + b[i] < both[j]:
			ti += a[i] + b[i]
			i += 1
		elif a[i] + b[i] >= both[j]:
			ti += both[j]
			j += 1
		li += 1
	print(ti)


from operator import add

class SegTree:

	def __init__(self, N, e, operator_func=add):
		self.e = e
		self.size = N
		self.node = [self.e] * (2 * N)
		self.operator_func = operator_func

	def set_list(self, l):
		for i in range(self.size):
			self.node[i + self.size - 1] = l[i]
		for i in range(self.size - 1)[::-1]:
			self.node[i] = self.operator_func(self.node[2 * i + 1], self.node[2 * i + 2])

	def update(self, k, x):
		k += self.size - 1
		self.node[k] = x
		while k >= 0:
			k = (k - 1) // 2
			self.node[k] = self.operator_func(self.node[2 * k + 1], self.node[2 * k + 2])

	def get(self, l, r):
		x = self.e
		l += self.size
		r += self.size
		while l < r:
			if l & 1:
				x = self.operator_func(x, self.node[l - 1])
				l += 1
			if r & 1:
				r -= 1
				x = self.operator_func(x, self.node[r - 1])
			l >>= 1
			r >>= 1
		return x
(n, k) = map(int, input().split())
(l1, l2, l3) = ([], [], [])
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a == 0 and b == 0:
		continue
	elif a and b:
		l2.append(t)
	elif a:
		l1.append(t)
	else:
		l3.append(t)
l1.sort()
l2.sort()
l3.sort()
(s1, s2, s3) = (len(l1), len(l2), len(l3))
tree1 = SegTree(s1, 0, add)
tree2 = SegTree(s2, 0, add)
tree3 = SegTree(s3, 0, add)
tree1.set_list(l1)
tree2.set_list(l2)
tree3.set_list(l3)
INF = 10 ** 20
ans = INF
for i in range(k + 1):
	if i <= s2 and k - i <= s1 and (k - i <= s3):
		p = max(0, k - i)
		v = tree2.get(0, i) + tree1.get(0, p) + tree3.get(0, p)
		ans = min(ans, v)
print(ans if ans != INF else -1)


(n, k) = map(int, input().split())
a = []
b = []
c = []
for i in range(n):
	m = [*map(int, input().split())]
	if m[1] == 1 and m[2] == 1:
		c.append(m[0])
	elif m[1] == 1:
		a.append(m)
	elif m[2] == 1:
		b.append(m)
a.sort(key=lambda x: x[0])
b.sort(key=lambda x: x[0])
for i in range(min(len(a), len(b))):
	c.append(a[i][0] + b[i][0])
c.sort()
if len(c) < k:
	print(-1)
else:
	print(sum((c[i] for i in range(k))))


def next():
	return [int(x) for x in input().split()]

class book:

	def __init__(self, t, a, b):
		self.t = t
		self.a = a
		self.b = b
(n, k) = next()
books = []
for _ in range(n):
	(t, a, b) = next()
	books.append(book(t, a, b))
oo = list(map(lambda x: x.t, filter(lambda x: x.a == 1 and x.b == 1, books)))
zo = list(sorted(map(lambda x: x.t, filter(lambda x: x.a == 0 and x.b == 1, books))))
oz = list(sorted(map(lambda x: x.t, filter(lambda x: x.a == 1 and x.b == 0, books))))
mi = min(len(zo), len(oz))
for i in range(mi):
	oo.append(zo[i] + oz[i])
if len(oo) < k:
	print(-1)
else:
	print(sum(sorted(oo)[:k]))


l = list(map(int, input().split()))
(n, y) = (l[0], l[1])
fir = []
sec = []
bot = []
for _ in range(n):
	k = list(map(int, input().split()))
	if k[1] == 1 and k[2] == 1:
		bot.append(k[0])
	elif k[1] == 1 and k[2] == 0:
		fir.append(k[0])
	elif k[1] == 0 and k[2] == 1:
		sec.append(k[0])
f = len(fir)
s = len(sec)
b = len(bot)
if f + b < y or s + b < y:
	print(-1)
else:
	fir.sort()
	sec.sort()
	bot.sort()
	if f < y:
		fir += (y - f) * [10001]
	else:
		fir = fir[0:y]
	if s < y:
		sec += (y - s) * [10001]
	else:
		sec = sec[0:y]
	val = sum(fir) + sum(sec)
	fir.reverse()
	sec.reverse()
	for i in range(y):
		try:
			if fir[i] + sec[i] > bot[i]:
				val = val - fir[i] - sec[i] + bot[i]
		except:
			break
	print(val)


for _ in range(1):
	(n, k) = map(int, input().split())
	one = []
	two = []
	both = []
	a = []
	for ii in range(n):
		(x, y, z) = map(int, input().split())
		a.append([x, y, z])
		if z * y:
			both.append(x)
		else:
			if z:
				two.append(x)
			if y:
				one.append(x)
	both.sort()
	one.sort()
	two.sort()
	ans = 0
	tot = k
	bo = len(both)
	on = len(one)
	tw = len(two)
	if bo + min(on, tw) < k:
		print(-1)
	else:
		i = 0
		if bo < k:
			for i in range(k - bo):
				ans += one[i] + two[i]
				tot -= 1
			i += 1
		c = 0
		while tot:
			if i >= on or i >= tw:
				break
			if one[i] + two[i] < both[c]:
				ans += one[i] + two[i]
				i += 1
				tot -= 1
			else:
				ans += both[c]
				c += 1
				tot -= 1
		while tot:
			ans += both[c]
			c += 1
			tot -= 1
		print(ans)


(n, k) = tuple(map(int, input().split()))
alice = []
bob = []
both = []
for _ in range(n):
	(t, a, b) = tuple(map(int, input().split()))
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
both.sort()
alice.sort()
bob.sort()
remain = 0
if k <= len(both):
	result = sum(both[:k])
else:
	remain = k - len(both)
	if remain > len(bob) or remain > len(alice):
		result = -1
	else:
		result = sum(both)
		result += sum(alice[:remain]) + sum(bob[:remain])
index = max(0, k - len(both))
lenbob = len(bob)
lenalice = len(alice)
if result != -1:
	for i in range(min(k, len(both)) - 1, -1, -1):
		if index > lenbob - 1 or index > lenalice - 1:
			break
		newresult = result - both[i] + alice[index] + bob[index]
		index += 1
		if newresult < result:
			result = newresult
		else:
			break
print(result)


def main():
	import sys
	input = sys.stdin.buffer.readline
	(n, k) = map(int, input().split())
	tab = [tuple(map(int, input().split())) for i in range(n)]
	tab.sort(reverse=True)
	A = [tab[i][0] for i in range(n) if tab[i][1] == 1 and tab[i][2] == 0]
	B = [tab[i][0] for i in range(n) if tab[i][1] == 0 and tab[i][2] == 1]
	AB = [tab[i][0] for i in range(n) if tab[i][1] == tab[i][2] == 1]
	count = 0
	ans = 0
	ab = 0
	apb = 0
	while count < k:
		if len(AB) > 0:
			ab = AB[-1]
		else:
			ab = 10 ** 10
		if len(A) > 0 and len(B) > 0:
			apb = A[-1] + B[-1]
		else:
			apb = 10 ** 10
		if ab < apb:
			ans += ab
			if len(AB):
				AB.pop()
		else:
			ans += apb
			if len(A):
				A.pop()
			if len(B):
				B.pop()
		count += 1
	if ans >= 10 ** 10:
		print(-1)
	else:
		print(ans)
main()


from heapq import heappush, heappush, heapify
(n, k) = map(int, input().split())
alice = []
bob = []
both = []
for i in range(n):
	(t, a, b) = map(int, input().rstrip().split())
	if a == 1 and b == 1:
		both.append(t)
	if a == 1 and b == 0:
		alice.append(t)
	if a == 0 and b == 1:
		bob.append(t)
if len(alice) + len(both) < k or len(bob) + len(both) < k:
	print(-1)
	exit()
alice.sort()
bob.sort()
both.sort()
ans = 0
m = len(both)
n = min(len(alice), len(bob))
i = 0
j = 0
while k > 0:
	both_t = float('inf')
	ab_t = float('inf')
	if i < m:
		both_t = both[i]
	if j < n:
		ab_t = alice[j] + bob[j]
	if both_t <= ab_t:
		ans += both_t
		k -= 1
		i += 1
	else:
		ans += ab_t
		j += 1
		k -= 1
print(ans)


import sys
input = sys.stdin.readline
from math import ceil
(n, k) = map(int, input().split())
Bob = []
Alice = []
Together = []
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a * b == 1:
		Together.append(t)
	elif a == 1:
		Alice.append(t)
	elif b == 1:
		Bob.append(t)
if len(Bob) + len(Together) < k or len(Alice) + len(Together) < k:
	print(-1)
	exit()
Bob.sort()
Alice.sort()
Together.sort()
a = 0
b = 0
t = 0
T = 0
Total_Bob = 0
Total_Alice = 0
while Total_Bob < k or Total_Alice < k:
	if Total_Alice < k and Total_Bob < k:
		if t < len(Together) and a < len(Alice) and (b < len(Bob)):
			if Together[t] < Alice[a] + Bob[b]:
				T += Together[t]
				t += 1
				Total_Alice += 1
				Total_Bob += 1
			else:
				T += Alice[a]
				T += Bob[b]
				a += 1
				b += 1
				Total_Alice += 1
				Total_Bob += 1
		elif t >= len(Together):
			T += Alice[a]
			T += Bob[b]
			a += 1
			b += 1
			Total_Alice += 1
			Total_Bob += 1
		else:
			T += Together[t]
			Total_Alice += 1
			Total_Bob += 1
			t += 1
	elif Total_Alice < k:
		if t < len(Together) and a < len(Alice):
			if Together[t] < Alice[a]:
				T += Together[t]
				t += 1
				Total_Alice += 1
				Total_Bob += 1
			else:
				T += Alice[a]
				a += 1
				Total_Alice += 1
		elif t >= len(Together):
			T += Alice[a]
			a += 1
			Total_Alice += 1
		else:
			T += Together[t]
			t += 1
			Total_Alice += 1
			Total_Bob += 1
	elif t < len(Together) and b < len(Bob):
		if Together[t] < Bob[b]:
			T += Together[t]
			Total_Bob += 1
			t += 1
			Total_Alice += 1
		else:
			T += Bob[b]
			Total_Bob += 1
			b += 1
	elif t >= len(Together):
		T += Bob[b]
		Total_Bob += 1
		b += 1
	else:
		T += Together[t]
		Total_Bob += 1
		t += 1
		Total_Alice += 1
print(T)


(n, k) = map(int, input().strip().split())
not_possible = False
(alice_only, bob_only, both) = ([], [], [])
(alice_likes, bob_likes) = (0, 0)
total_time = 0
for _ in range(n):
	(t, alice, bob) = map(int, input().strip().split())
	alice_likes += alice
	bob_likes += bob
	if alice + bob == 2:
		both.append(t)
	elif alice:
		alice_only.append(t)
	elif bob:
		bob_only.append(t)
	if alice + bob > 0:
		total_time += t
if alice_likes < k or bob_likes < k:
	not_possible = True
alice_remove = alice_likes - k
bob_remove = bob_likes - k
both_remove = min(alice_remove, bob_remove)
alice_remove -= both_remove
bob_remove -= both_remove
both.sort(reverse=True)
alice_only.sort(reverse=True)
bob_only.sort(reverse=True)
(a, b) = (0, 0)
while a < len(alice_only) and alice_remove > 0:
	total_time -= alice_only[a]
	a += 1
	alice_remove -= 1
while b < len(bob_only) and bob_remove > 0:
	total_time -= bob_only[b]
	b += 1
	bob_remove -= 1
alice_only = alice_only[a:]
bob_only = bob_only[b:]
(ab, o) = (0, 0)
while both_remove > 0:
	(curr_ab, curr_both) = (0, 0)
	if ab < len(alice_only) and ab < len(bob_only):
		curr_ab = alice_only[ab] + bob_only[ab]
	if o < len(both):
		curr_both = both[o]
	if curr_ab + curr_both == 0:
		break
	if curr_ab > curr_both:
		total_time -= curr_ab
		ab += 1
	else:
		total_time -= curr_both
		o += 1
	both_remove -= 1
alice_remove += both_remove
bob_remove += both_remove
(a, b) = (ab, ab)
while a < len(alice_only) and alice_remove > 0:
	total_time -= alice_only[a]
	a += 1
	alice_remove -= 1
while b < len(bob_only) and bob_remove > 0:
	total_time -= bob_only[b]
	b += 1
	bob_remove -= 1
if not_possible:
	print(-1)
else:
	print(total_time)


from collections import defaultdict
(n, k) = list(map(int, input().split()))
d = defaultdict(list)
for i in range(n):
	(t, a, b) = list(map(int, input().split()))
	x = int(str(a) + str(b), 2)
	d[x].append(t)
if len(d[2]) + len(d[3]) < k or len(d[1]) + len(d[3]) < k:
	print(-1)
else:
	d[1].sort()
	d[2].sort()
	d[3].sort()
	(i, j, l) = (0, 0, 0)
	c = 0
	s = 0
	while c < k:
		if l < len(d[3]):
			if i < len(d[1]):
				if j < len(d[2]):
					if d[1][i] + d[2][j] < d[3][l]:
						s += d[1][i] + d[2][j]
						i += 1
						j += 1
					else:
						s += d[3][l]
						l += 1
				else:
					s += d[3][l]
					l += 1
			else:
				s += d[3][l]
				l += 1
		else:
			s += d[1][i] + d[2][j]
			i += 1
			j += 1
		c += 1
	print(s)


from sys import stdin, exit
input = stdin.readline

def i():
	return input()

def ii():
	return int(input())

def iis():
	return map(int, input().split())

def liis():
	return list(map(int, input().split()))

def print_array(a):
	print(' '.join(map(str, a)))
(n, k) = iis()
alice = []
bob = []
both = []
for _ in range(n):
	(t, a, b) = iis()
	if a == 1 and b == 0:
		alice.append(t)
	elif a == 0 and b == 1:
		bob.append(t)
	elif a == 1 and b == 1:
		both.append(t)
alice = sorted(alice)[::-1]
bob = sorted(bob)[::-1]
both = sorted(both)[::-1]
time = 0
livros = 0
while k > 0 and (len(both) != 0 or (len(alice) != 0 and len(bob) != 0)):
	if len(both) and len(alice) and len(bob):
		separado = alice[-1] + bob[-1]
		junto = both[-1]
		if junto < separado:
			time += junto
			both.pop()
		else:
			time += separado
			alice.pop()
			bob.pop()
	elif len(both):
		time += both.pop()
	elif len(alice) and len(bob):
		time += alice.pop()
		time += bob.pop()
	else:
		continue
	k -= 1
if k == 0:
	print(time)
else:
	print(-1)


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
(o, a, b) = ([], [], [])
for i in range(n):
	(q, w, e) = map(int, input().split())
	if w == e and w:
		o.append(q)
	elif w and (not e):
		a.append(q)
	elif w or e:
		b.append(q)
i = j = l = 0
done = 0
ans = 0
o.sort()
a.sort()
b.sort()
while (i < len(o) or (j < len(a) and l < len(b))) and done < k:
	if i < len(o) and (j >= len(a) or l >= len(b) or (j < len(a) and l < len(b) and (o[i] <= a[j] + b[l]))):
		ans += o[i]
		i += 1
		done += 1
	elif l < len(b) and j < len(a):
		ans += a[j] + b[l]
		j += 1
		l += 1
		done += 1
print(ans if done >= k else -1)


(n, k) = [int(x) for x in input().split()]
both = []
bob = []
alice = []
for i in range(n):
	(t, a, b) = [int(x) for x in input().split()]
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
both.sort()
bob.sort()
alice.sort()
y = max(k - min(len(bob), len(alice)), 0)
soma_both = 0
sa = 0
sb = 0
poss = len(both) + min(len(alice), len(bob)) >= k
if poss:
	for i in range(y):
		soma_both += both[i]
	for i in range(max(k - y, 0)):
		sa += alice[i]
	for i in range(max(k - y, 0)):
		sb += bob[i]
	ptr1 = k - y
	ptr2 = k - y
	resposta = sa + sb + soma_both
	for i in range(y, len(both)):
		ptr1 -= 1
		ptr2 -= 1
		if ptr2 == -1 or ptr1 == -1:
			break
		soma_both += both[i]
		sa -= alice[ptr1]
		sb -= bob[ptr2]
		if soma_both + sa + sb >= 0:
			resposta = min(resposta, soma_both + sa + sb)
	print(resposta)
else:
	print(-1)


(n, k) = map(int, input().split())
obaja = []
bob = []
alice = []
a = 0
b = 0
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a == 1:
		if b == 1:
			obaja.append(t)
		else:
			alice.append(t)
	elif b == 1:
		bob.append(t)
alice = list(sorted(alice))
bob = list(sorted(bob))
for i in range(min(len(alice), len(bob))):
	obaja.append(alice[i] + bob[i])
obaja = list(sorted(obaja))
if len(obaja) < k:
	print(-1)
else:
	ans = 0
	for i in range(k):
		ans += obaja[i]
	print(ans)


(n, k) = [int(x) for x in input().split()]
books = []
books_a = []
books_b = []
for i in range(n):
	b = [int(x) for x in input().split()]
	if b[1] == 1 and b[2] == 1:
		books.append(b[0])
	elif b[1] == 1:
		books_a.append(b[0])
	elif b[2] == 1:
		books_b.append(b[0])
books_a = sorted(books_a)
books_b = sorted(books_b)
z = min(len(books_a), len(books_b))
for j in range(z):
	books.append(books_a[j] + books_b[j])
books = sorted(books)
ans = 0
if len(books) < k:
	print(-1)
else:
	for f in range(k):
		ans += books[f]
	print(ans)


import sys
inp = [int(x) for x in sys.stdin.read().split()]
ii = 0
(n, k) = inp[ii:ii + 2]
ii += 2
(both, a, b) = ([], [], [])
for i in range(n):
	(x, p, q) = inp[ii:ii + 3]
	ii += 3
	if p and q:
		both.append(x)
	elif p:
		a.append(x)
	elif q:
		b.append(x)
if len(both) + len(a) < k or len(both) + len(b) < k:
	print(-1)
else:
	res = 2 * 10 ** 9
	both.sort()
	a.sort()
	b.sort()
	(cnt, tot, i, j) = (len(both), sum(both[0:min(len(both), k)]), 0, 0)
	for cnt in range(min(len(both), k), max(k - min(len(a), len(b)), 0) - 1, -1):
		while i < k - cnt:
			tot += a[i]
			i += 1
		while j < k - cnt:
			tot += b[j]
			j += 1
		res = min(res, tot)
		if cnt > 0:
			tot -= both[cnt - 1]
	print(res)


(n, k) = map(int, input().split())
a = []
for i in range(n):
	(x, y, z) = map(int, input().split())
	a.append([x, y, z])
alice_count = 0
bob_count = 0
alice = []
bob = []
combine = []
for i in range(n):
	if a[i][1] == 1 and a[i][2] == 1:
		combine.append(a[i][0])
		alice_count += 1
		bob_count += 1
	elif a[i][1] == 1:
		alice.append(a[i][0])
		alice_count += 1
	elif a[i][2] == 1:
		bob.append(a[i][0])
		bob_count += 1
if alice_count < k or bob_count < k:
	print('-1')
else:
	alice_len = len(alice)
	bob_len = len(bob)
	combine_len = len(combine)
	alice.sort()
	bob.sort()
	combine.sort()
	ans = 0
	i1 = 0
	i2 = 0
	while i1 + i2 < k:
		if i1 < bob_len and i1 < alice_len and (i2 < combine_len):
			if bob[i1] + alice[i1] > combine[i2]:
				ans += combine[i2]
				i2 += 1
			else:
				ans += bob[i1] + alice[i1]
				i1 += 1
		elif i1 >= bob_len or i1 >= alice_len:
			ans += combine[i2]
			i2 += 1
		elif i2 >= combine_len:
			ans += bob[i1] + alice[i1]
			i1 += 1
	print(ans)


(n, k) = map(int, input().split())
l1 = []
l2 = []
l3 = []
n1 = n2 = n3 = 0
for i in range(n):
	(a, b, c) = map(int, input().split())
	if b == c == 1:
		l1.append(a)
		n1 += 1
	elif b == 1:
		l2.append(a)
		n2 += 1
	elif c == 1:
		l3.append(a)
		n3 += 1
if n1 + n2 < k or n1 + n3 < k:
	print(-1)
else:
	l1.sort()
	l2.sort()
	l3.sort()
	s1 = s2 = s = 0
	p = min(n2, n3)
	z1 = []
	for i in range(p):
		s1 += l2[i]
		s1 += l3[i]
		z1.append(s1)
		s1 = 0
	z2 = z1 + l1
	z2.sort()
	if len(z2) < k:
		print(-1)
	else:
		for i in range(k):
			s += z2[i]
		print(s)


(n, k) = map(int, input().split())
(common, alice, bob) = ([0], [0], [0])
for i in range(n):
	(t, a, b) = map(int, input().split())
	if a + b == 2:
		common.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
common.sort()
alice.sort()
bob.sort()
for i in range(1, len(common)):
	common[i] += common[i - 1]
for i in range(1, len(alice)):
	alice[i] += alice[i - 1]
for i in range(1, len(bob)):
	bob[i] += bob[i - 1]
ans = 10 ** 20
for i in range(len(common)):
	t = common[i]
	r = k - i
	if r >= 0 and r < len(alice) and (r < len(bob)):
		t += alice[r] + bob[r]
		ans = min(ans, t)
if ans < 10 ** 20:
	print(ans)
else:
	print(-1)


(n, k) = map(int, input().split())
(a, b, c) = ([], [], [])
for i in range(n):
	(t, x, y) = map(int, input().split())
	if x == 1 and y == 1:
		a.append(t)
	if x == 1 and y == 0:
		b.append(t)
	if x == 0 and y == 1:
		c.append(t)
a.sort()
b.sort()
c.sort()
(prea, preb, prec) = (0, 0, 0)
cnt = min(len(b), len(c), k)
for i in range(cnt):
	preb += b[i]
	prec += c[i]
bestans = int(2000000000.0 + 5)
if cnt == k:
	bestans = preb + prec
for both in range(min(len(a), k)):
	prea += a[both]
	idx = k - both - 1
	if idx < cnt:
		preb -= b[idx]
		prec -= c[idx]
	if idx - 1 < cnt and prea + preb + prec < bestans:
		bestans = prea + preb + prec
print(bestans) if bestans <= int(2000000000.0) else print(-1)


(n, k) = map(int, input().split())
y = []
x = []
z = []
for i in range(n):
	(a, b, c) = map(int, input().split())
	if b == 1 and c == 0:
		x.append(a)
	if c == 1 and b == 0:
		y.append(a)
	if b == 1 and c == 1:
		z.append(a)
x = sorted(x)
y = sorted(y)
z = sorted(z)
for i in range(1, len(x)):
	x[i] += x[i - 1]
for i in range(1, len(y)):
	y[i] += y[i - 1]
for i in range(1, len(z)):
	z[i] += z[i - 1]
if len(x) + len(z) < k or len(y) + len(z) < k:
	print(-1)
else:
	ans = float('inf')
	if len(x) >= k and len(y) >= k:
		ans = x[k - 1] + y[k - 1]
	if len(z) >= k:
		ans = min(z[k - 1], ans)
	if x and y:
		for i in range(len(z)):
			if k - i - 1 - 1 < len(x) and k - i - 1 - 1 < len(y) and (k - i + 2 >= 0):
				ans = min(ans, z[i] + x[k - i - 2] + y[k - i - 2])
	print(ans)


(book, k) = map(int, input().split())
(both, alice, bob) = ([], [], [])
for i in range(book):
	(time, x, y) = map(int, input().split())
	if x == 1 and y == 1:
		both.append(time)
	elif x == 1 and y == 0:
		alice.append(time)
	elif x == 0 and y == 1:
		bob.append(time)
if len(both) + len(alice) < k or len(both) + len(bob) < k:
	print(-1)
else:
	both.sort()
	alice.sort()
	bob.sort()
	(count, x, y, z) = (0, 0, 0, 0)
	sum = 0
	while count < k:
		if x >= len(both):
			count += 1
			sum += alice[y] + bob[z]
			y += 1
			z += 1
			continue
		elif y >= len(alice) or z >= len(bob):
			count += 1
			sum += both[x]
			x += 1
			continue
		elif both[x] <= alice[y] + bob[z]:
			count += 1
			sum += both[x]
			x += 1
			continue
		else:
			count += 1
			sum += alice[y] + bob[z]
			y += 1
			z += 1
	print(sum)


(n, k) = map(int, input().split())
alice = []
bob = []
both = []
for _ in range(n):
	(t, a, b) = map(int, input().split())
	if a and b:
		both.append(t)
	elif a:
		alice.append(t)
	elif b:
		bob.append(t)
if len(alice) + len(both) < k or len(bob) + len(both) < k:
	print(-1)
else:
	alice.sort()
	bob.sort()
	both.sort()
	i = j = 0
	ans = 0
	while i < len(alice) and i < len(bob) and (j < len(both)) and (k > 0):
		if alice[i] + bob[i] < both[j]:
			ans += alice[i] + bob[i]
			i += 1
		else:
			ans += both[j]
			j += 1
		k -= 1
	if k:
		if j >= len(both):
			while k > 0:
				ans += alice[i] + bob[i]
				i += 1
				k -= 1
		else:
			while k > 0:
				ans += both[j]
				j += 1
				k -= 1
	print(ans)


(n, k) = list(map(int, input().strip().split()))
alice = []
bob = []
both = []
for _ in range(n):
	(t, a, b) = list(map(int, input().strip().split()))
	if a == 1 and b == 1:
		both.append(t)
	elif a == 1:
		alice.append(t)
	elif b == 1:
		bob.append(t)
alice.sort()
bob.sort()
both.sort()
done = 0
i = 0
j = 0
time = 0
i_max = min(len(alice), len(bob))
j_max = len(both)
while (i < i_max or j < j_max) and done < k:
	if i < i_max and j < j_max:
		done += 1
		if alice[i] + bob[i] < both[j]:
			time += alice[i] + bob[i]
			i += 1
		else:
			time += both[j]
			j += 1
	elif i < i_max:
		done += 1
		time += alice[i] + bob[i]
		i += 1
	else:
		done += 1
		time += both[j]
		j += 1
if done < k:
	print(-1)
else:
	print(time)


(n, k) = map(int, input().split())
inf = float('inf')
(a, b, c) = ([inf], [inf], [inf])
(a_cnt, b_cnt) = (0, 0)
for i in range(n):
	(u, v, w) = map(int, input().split())
	if v == 1 and w == 1:
		c.append(u)
		a_cnt += 1
		b_cnt += 1
	elif v == 1:
		a.append(u)
		a_cnt += 1
	elif w == 1:
		b.append(u)
		b_cnt += 1
if a_cnt < k or b_cnt < k:
	print(-1)
	exit()
a.sort(reverse=True)
b.sort(reverse=True)
c.sort(reverse=True)
(a_left, b_left, ans) = (k, k, 0)
while a_left > 0 or b_left > 0:
	if a_left and b_left and len(a) - 1 and len(b) - 1 and len(c) - 1:
		if a[-1] + b[-1] >= c[-1] or len(a) - 1 < a_left or len(b) - 1 < b_left:
			ans += c.pop()
		else:
			ans += a.pop() + b.pop()
		a_left -= 1
		b_left -= 1
	else:
		best = inf
		if a_left and b_left:
			best = min(best, a[-1] + b[-1])
		if a_left and (not b_left):
			best = min(best, a[-1])
		if b_left and (not a_left):
			best = min(best, b[-1])
		best = min(best, c[-1])
		if best == c[-1]:
			ans += c.pop()
			a_left -= 1
			b_left -= 1
		elif best == a[-1]:
			ans += a.pop()
			a_left -= 1
		else:
			ans += b.pop()
			b_left -= 1
print(ans)


(n, ke) = [int(i) for i in input().split()]
bo = []
a1 = []
b1 = []
for i in range(n):
	(ti, a, b) = [int(i) for i in input().split()]
	if a == 1 and b == 1:
		bo.append([ti, a, b])
	elif a == 1:
		a1.append([ti, a, b])
	elif b == 1:
		b1.append([ti, a, b])
bo.sort()
a1.sort()
b1.sort()
su = 0
i = 0
j = 0
k = 0
f1 = 0
while ke > 0:
	if i + 1 > len(bo) or (j + 1 > len(a1) or k + 1 > len(b1)):
		f1 = 1
		break
	elif bo[i][0] <= a1[j][0] + b1[k][0]:
		su += bo[i][0]
		i += 1
		ke -= 1
	elif bo[i][0] > a1[j][0] + b1[k][0]:
		su += a1[j][0] + b1[k][0]
		ke -= 1
		j += 1
		k += 1
	elif bo[i][0] == a1[j][0] + b1[k][0]:
		if len(bo) >= min(len(a1), len(b1)):
			su += bo[i][0]
			i += 1
			ke -= 1
		else:
			su += a1[j][0] + b1[k][0]
			j += 1
			k += 1
			ke -= 1
if ke > 0 and i + 1 > len(bo) and (j + 1 > len(a1) and k + 1 > len(b1)):
	print(-1)
elif f1 == 0:
	print(su)
elif i + 1 > len(bo):
	if j + ke <= len(a1) and k + ke <= len(b1):
		while ke > 0:
			su += a1[j][0] + b1[k][0]
			ke -= 1
			j += 1
			k += 1
		print(su)
	else:
		print(-1)
elif j + 1 > len(a1) or k + 1 > len(b1):
	if i + ke <= len(bo):
		while ke > 0:
			su += bo[i][0]
			i += 1
			ke -= 1
		print(su)
	else:
		print(-1)
else:
	print(-1)


(n, k) = map(int, input().split())
times = [[], [], [], []]
for i in range(n):
	(t, a, b) = map(int, input().split())
	times[a * 2 + b].append(t)
for i in range(1, 4):
	times[i].sort()
sums = []
for i in range(len(times)):
	sums.append([])
	for j in range(len(times[i])):
		if j == 0:
			sums[i].append(times[i][0])
		else:
			sums[i].append(times[i][j] + sums[i][j - 1])
sums[1].insert(0, 0)
sums[2].insert(0, 0)
sums[3].insert(0, 0)
ans = 10 ** 10
for i in range(min(k + 1, len(sums[-1]))):
	if k - i < len(sums[1]) and k - i < len(sums[2]):
		ans = min(ans, sums[3][i] + sums[1][k - i] + sums[2][k - i])
if ans == 10 ** 10:
	ans = -1
print(ans)


def min_time(tot_books, books_like, read_time, a_time, b_time):
	time = []
	temp_a = []
	temp_b = []
	if min(sum(a_time), sum(b_time)) >= books_like:
		for x in range(tot_books):
			if a_time[x] == b_time[x] == 1:
				time.append(read_time[x])
			elif a_time[x] == 0 and b_time[x] == 1:
				temp_b.append(read_time[x])
			elif a_time[x] == 1 and b_time[x] == 0:
				temp_a.append(read_time[x])
		(temp_a.sort(), temp_b.sort())
		for y in range(min(len(temp_a), len(temp_b))):
			time.append(temp_a[y] + temp_b[y])
		time.sort()
		time = time[:books_like]
		return sum(time)
	else:
		return -1
(n, k) = map(int, input().split())
t = []
a = []
b = []
for i in range(n):
	(x, y, z) = map(int, input().split())
	(t.append(x), a.append(y), b.append(z))
print(min_time(n, k, t, a, b))


(n, k) = list(map(int, input().split()))
(l, l1, l2) = ([], [], [])
for _ in range(n):
	(x, y, z) = list(map(int, input().split()))
	if y == 1 and z == 1:
		l.append(x)
	elif y == 1:
		l1.append([x, y, z])
	elif z == 1:
		l2.append([x, y, z])
l1.sort()
l2.sort()
for i in range(min(k, len(l1), len(l2))):
	a = l1[i][0]
	b = l2[i][0]
	l.append(a + b)
l.sort()
if len(l) >= k:
	print(sum(l[:k]))
else:
	print(-1)


import sys
inp = [int(x) for x in sys.stdin.read().split()]
ii = 0
n = inp[ii]
ii += 1
k = inp[ii]
ii += 1
T = inp[ii + 0:ii + 3 * n:3]
A = inp[ii + 1:ii + 3 * n:3]
B = inp[ii + 2:ii + 3 * n:3]
TA = []
TB = []
TAB = []
for i in range(n):
	if A[i] and B[i]:
		TAB.append(T[i])
	elif A[i]:
		TA.append(T[i])
	elif B[i]:
		TB.append(T[i])

def cumsummer(A):
	cumsum = [0]
	for a in A:
		cumsum.append(cumsum[-1] + a)
	return cumsum
TA.sort()
TB.sort()
TAB.sort()
n = len(TA)
m = len(TB)
nm = len(TAB)
TA = cumsummer(TA)
TB = cumsummer(TB)
TAB = cumsummer(TAB)
time = inf = 10 ** 9 * 2 + 100
for x in range(min(k, nm) + 1):
	y = z = k - x
	if n < y or m < z:
		continue
	time = min(time, TAB[x] + TA[y] + TB[z])
print(time if time != inf else -1)


import os
import sys
debug = True
if debug and os.path.exists('input.in'):
	input = open('input.in', 'r').readline
else:
	debug = False
	input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())
test_count = 1
if debug:
	test_count = inp()
for t in range(test_count):
	if debug:
		print('Test Case #', t + 1)
	(n, k) = invr()
	books = [None] * n
	alice = []
	bob = []
	both = []
	for i in range(n):
		books[i] = inlt()
	books.sort()
	ans = 0
	done = False
	for book in books:
		if book[1] == 1 and book[2] == 1:
			both.append(book[0])
		elif book[1] == 1:
			alice.append(book[0])
		elif book[2] == 1:
			bob.append(book[0])
	c = 0
	cnt = 0
	while k > 0 and cnt < min(len(alice), len(bob)):
		if c < len(both) and alice[cnt] + bob[cnt] > both[c]:
			ans += both[c]
			c += 1
		else:
			ans += alice[cnt] + bob[cnt]
			cnt += 1
		k -= 1
	for i in range(k):
		if c < len(both):
			ans += both[c]
			k -= 1
			c += 1
	if k != 0:
		print(-1)
	else:
		print(ans)


from sys import *
from math import *
(n, k) = map(int, stdin.readline().split())
(x, y, z) = ([], [], [])
for i in range(n):
	(t, a, b) = map(int, stdin.readline().split())
	if a and b:
		z.append(t)
	elif a:
		x.append(t)
	elif b:
		y.append(t)
x.sort()
y.sort()
for i in range(min(len(x), len(y))):
	z.append(x[i] + y[i])
z.sort()
if len(z) < k:
	print(-1)
else:
	ans = 0
	for i in range(k):
		ans += z[i]
	print(ans)


import sys
import functools
[n, k] = [int(i) for i in sys.stdin.readline().split()]
arr = []
for x in range(n):
	[t, a, b] = [int(j) for j in sys.stdin.readline().split()]
	arr.append([t, a, b])
alice = 0
bob = 0
for g in range(n):
	if arr[g][1] == 1:
		alice += 1
	if arr[g][2] == 1:
		bob += 1
if alice < k or bob < k:
	print(-1)
else:
	comb_arr = []
	f_arr = []
	s_arr = []
	for p in range(n):
		if arr[p][1] == 1 and arr[p][2] == 1:
			comb_arr.append(arr[p][0])
		elif arr[p][1] == 1:
			f_arr.append(arr[p][0])
		elif arr[p][2] == 1:
			s_arr.append(arr[p][0])
	f_arr.sort()
	s_arr.sort()
	for c in range(min(len(f_arr), len(s_arr))):
		comb_arr.append(f_arr[c] + s_arr[c])
	comb_arr.sort()
	ans = sum(comb_arr[:k])
	print(ans)