Elections in Berland are coming. There are only two candidates — Alice and Bob.

The main Berland TV channel plans to show political debates. There are $n$ people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views:  supporting none of candidates (this kind is denoted as "00"),  supporting Alice but not Bob (this kind is denoted as "10"),  supporting Bob but not Alice (this kind is denoted as "01"),  supporting both candidates (this kind is denoted as "11"). 

The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions:  at least half of spectators support Alice (i.e. $2 \cdot a \ge m$, where $a$ is number of spectators supporting Alice and $m$ is the total number of spectators),  at least half of spectators support Bob (i.e. $2 \cdot b \ge m$, where $b$ is number of spectators supporting Bob and $m$ is the total number of spectators),  the total influence of spectators is maximal possible. 

Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.


-----Input-----

The first line contains integer $n$ ($1 \le n \le 4\cdot10^5$) — the number of people who want to take part in the debate as a spectator.

These people are described on the next $n$ lines. Each line describes a single person and contains the string $s_i$ and integer $a_i$ separated by space ($1 \le a_i \le 5000$), where $s_i$ denotes person's political views (possible values — "00", "10", "01", "11") and $a_i$ — the influence of the $i$-th person.


-----Output-----

Print a single integer — maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.


-----Examples-----
Input
6
11 6
10 4
01 3
00 3
00 7
00 9

Output
22

Input
5
11 1
01 1
00 100
10 1
01 1

Output
103

Input
6
11 19
10 22
00 18
00 29
11 29
10 28

Output
105

Input
3
00 5000
00 5000
00 5000

Output
0



-----Note-----

In the first example $4$ spectators can be invited to maximize total influence: $1$, $2$, $3$ and $6$. Their political views are: "11", "10", "01" and "00". So in total $2$ out of $4$ spectators support Alice and $2$ out of $4$ spectators support Bob. The total influence is $6+4+3+9=22$.

In the second example the direction can select all the people except the $5$-th person.

In the third example the direction can select people with indices: $1$, $4$, $5$ and $6$.

In the fourth example it is impossible to select any non-empty set of spectators.

Source: codeforces | Difficulty: MEDIUM
Tags: Greedy algorithms


Solutions:
from sys import stdin, stdout
from math import sqrt
import math
import heapq
from itertools import accumulate
N = int(input())
f = {}
f['00'] = []
f['10'] = []
f['01'] = []
f['11'] = []
for i in range(N):
	s = [x for x in stdin.readline().split()]
	f[s[0]].append(int(s[1]))
for key in f:
	f[key].sort(reverse=True)
s_X = sum(f['11'])
X = len(f['11'])
Y = len(f['10'])
Z = len(f['01'])
m = min(Y, Z)
s_Y = [0] * len(f['10'])
s = 0
for i in range(len(f['10'])):
	s += f['10'][i]
	s_Y[i] = s
s_Z = [0] * len(f['01'])
s = 0
for i in range(len(f['01'])):
	s += f['01'][i]
	s_Z[i] = s
res = 0
s = 0
for W in range(X + 1):
	if W > len(f['00']):
		break
	if W >= 1:
		s += f['00'][W - 1]
	bound = X - W
	if Y > Z:
		tmp_Y = min(Y, Z + bound)
		tmp_Z = Z
	elif Y == Z:
		tmp_Y = Y
		tmp_Z = Z
	elif Y < Z:
		tmp_Y = Y
		tmp_Z = min(Z, Y + bound)
	calculate = s_X + s
	if tmp_Y > 0:
		calculate += s_Y[tmp_Y - 1]
	if tmp_Z > 0:
		calculate += s_Z[tmp_Z - 1]
	res = max(res, calculate)
print(res)


m = int(input())
dou = 0
fir = []
sec = []
non = []
(d, f, s, n) = (0, 0, 0, 0)
for i in [0] * m:
	(a, b) = list(map(int, input().split()))
	if a == 11:
		dou += b
		d += 1
	elif a == 1:
		sec.append(b)
		s += 1
	elif a == 10:
		fir.append(b)
		f += 1
	else:
		non.append(b)
		n += 1
fir.sort(reverse=True)
sec.sort(reverse=True)
if not d + f * s:
	print(0)
	quit()
else:
	m = min(f, s)
	ans = dou + sum(fir[:m]) + sum(sec[:m])
	non = non + fir[m:] + sec[m:]
	non.sort(reverse=True)
	print(ans + sum(non[:d]))


n = int(input())
t_11 = []
t_10 = []
t_01 = []
t_00 = []
for x in range(n):
	tmp = list(input().split())
	supp = str(tmp[0])
	m = int(tmp[1])
	t_tmp = [supp, m]
	if supp == '11':
		t_11.append(t_tmp)
	elif supp == '01':
		t_01.append(t_tmp)
	elif supp == '10':
		t_10.append(t_tmp)
	else:
		t_00.append(t_tmp)
t_00 = sorted(t_00, key=lambda x: x[1])
t_10 = sorted(t_10, key=lambda x: x[1])
t_01 = sorted(t_01, key=lambda x: x[1])
t_11 = sorted(t_11, key=lambda x: x[1])
pop_a = 0
pop_b = 0
tot_inf = 0
pop_tot = 0
l_t_11 = len(t_11) - 1
for x in range(l_t_11, -1, -1):
	pop_a += 1
	pop_b += 1
	pop_tot += 1
	tot_inf += t_11[-1][1]
	del t_11[-1]
for x in range(min(len(t_10), len(t_01)) - 1, -1, -1):
	pop_b += 1
	pop_a += 1
	pop_tot += 2
	tot_inf += t_01[-1][1] + t_10[-1][1]
	del t_01[-1]
	del t_10[-1]
tmp_inf_1 = 0
tmp_inf_2 = 0
tmp_inf_3 = 0
tmp_t1 = []
tmp_t2 = []
if len(t_10) != 0:
	for x in t_10:
		tmp_t1.append(x)
	for x in t_00:
		tmp_t1.append(x)
	tmp_t1 = sorted(tmp_t1, key=lambda x: x[1])
	while True:
		if len(tmp_t1) == 0 or pop_a * 2 == pop_tot or pop_b * 2 == pop_a or (pop_b * 2 == pop_tot):
			break
		tot_inf += tmp_t1[-1][1]
		if tmp_t1[-1][0] == '10':
			pop_a += 1
			pop_tot += 1
		else:
			pop_tot += 1
		del tmp_t1[-1]
	print(tot_inf)
elif len(t_01) != 0:
	for x in t_01:
		tmp_t2.append(x)
	for x in t_00:
		tmp_t2.append(x)
	tmp_t2 = sorted(tmp_t2, key=lambda x: x[1])
	while True:
		if len(tmp_t2) == 0 or pop_b * 2 == pop_tot or pop_a * 2 == pop_b or (pop_a * 2 == pop_tot):
			break
		tot_inf += tmp_t2[-1][1]
		if tmp_t2[-1][0] == '01':
			pop_b += 1
			pop_tot += 1
		else:
			pop_tot += 1
		del tmp_t2[-1]
	print(tot_inf)
elif len(t_00) == 0:
	print(tot_inf)
	return
else:
	while True:
		if len(t_00) == 0 or pop_a * 2 == pop_tot or pop_b * 2 == pop_tot:
			break
		tot_inf += t_00[-1][1]
		pop_tot += 1
		del t_00[-1]
	print(tot_inf)


import math as ma
import sys
from sys import exit
from decimal import Decimal as dec
from itertools import permutations

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

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

def nu():
	return int(input())

def find_gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
n = nu()
al = []
bo = []
to = []
ze = []
for i in range(n):
	(x, y) = input().split()
	if x == '00':
		ze.append(int(y))
	if x == '11':
		to.append(int(y))
	if x == '10':
		al.append(int(y))
	if x == '01':
		bo.append(int(y))
al.sort(reverse=True)
bo.sort(reverse=True)
to.sort(reverse=True)
ze.sort(reverse=True)
zz = 0
if len(al) <= len(bo):
	zz = sum(al) + sum(bo[0:len(al)])
	gh = bo[len(al):] + ze
	zz = zz + sum(to)
	gh.sort(reverse=True)
	cc = 0
	for i in range(len(gh)):
		if cc == len(to):
			break
		zz += gh[i]
		cc += 1
	print(zz)
else:
	zz = sum(bo) + sum(al[0:len(bo)])
	gh = al[len(bo):] + ze
	zz = zz + sum(to)
	gh.sort(reverse=True)
	cc = 0
	for i in range(len(gh)):
		if cc == len(to):
			break
		zz += gh[i]
		cc += 1
	print(zz)


from collections import defaultdict
N = int(input())
num = 0
cnt = 0
rec = defaultdict(list)
cnt10 = 0
cnt01 = 0
for i in range(N):
	(a, b) = input().split()
	if a == '11':
		num += int(b)
		cnt += 1
	elif a == '01':
		cnt01 += 1
		rec[a].append(int(b))
	elif a == '10':
		cnt10 += 1
		rec[a].append(int(b))
	else:
		rec[a].append(int(b))
rec['10'] = sorted(rec['10'])
rec['01'] = sorted(rec['01'])
for i in range(min(cnt10, cnt01)):
	num += rec['10'].pop()
	num += rec['01'].pop()
q = rec['10'] + rec['01'] + rec['00']
q = sorted(q, reverse=True)
num += sum(q[:cnt])
print(num)


N = int(input())
A = [[] for _ in range(4)]
(a, b, c, d) = A
for ni in range(N):
	(v, f) = input().split()
	A[int(v, 2)].append(int(f))
for i in range(len(A)):
	A[i].sort(reverse=True)
ans = sum(A[3] or [0])
single = min(len(A[1]), len(A[2]))
ans += sum(A[1][:single] or [0])
ans += sum(A[2][:single] or [0])
x = len(A[3]) + single
a = A[1][single:] + A[2][single:] + A[0]
a.sort(reverse=True)
ans += sum(a[:len(A[3])] or [0])
print(ans)


import sys
read = lambda : sys.stdin.readline().strip()
readi = lambda : map(int, read().split())
from collections import *
n = int(read())
a = list()
b = list()
c = list()
d = list()
for _ in range(n):
	(type, val) = read().split()
	val = int(val)
	if type == '00':
		a.append(val)
	if type == '01':
		b.append(val)
	if type == '10':
		c.append(val)
	if type == '11':
		d.append(val)
b.sort(reverse=True)
c.sort(reverse=True)
peepsCanTake = 0
peopleCount = 0
influenceScore = 0
peopleCount += len(d)
influenceScore += sum(d)
peepsCanTake += peopleCount
bothPeeps = min(len(b), len(c))
peopleCount += bothPeeps
influenceScore += sum(b[:bothPeeps]) + sum(c[:bothPeeps])
b = b[bothPeeps:]
c = c[bothPeeps:]
temp = sorted(b + c + a, reverse=True)
influenceScore += sum(temp[:peepsCanTake])
print(influenceScore)


n = int(input())
no = []
a = []
b = []
bo = []
for _ in range(n):
	(t, s) = map(int, input().split())
	if t == 11:
		bo.append(s)
	elif t == 10:
		a.append(s)
	elif t == 1:
		b.append(s)
	else:
		no.append(s)
ans = 0
for i in bo:
	ans += i
a.sort(reverse=True)
b.sort(reverse=True)
if len(a) > len(b):
	for i in range(len(b)):
		ans += a[i]
		ans += b[i]
	for i in range(len(b), len(a)):
		no.append(a[i])
else:
	for i in range(len(a)):
		ans += a[i]
		ans += b[i]
	for i in range(len(a), len(b)):
		no.append(b[i])
no.sort(reverse=True)
for i in range(min(len(bo), len(no))):
	ans += no[i]
print(ans)


n = int(input())
s = [[], [], [], []]
for i in range(n):
	x = input().strip().split()
	if x[0] == '11':
		s[3].append(int(x[1]))
	elif x[0] == '10':
		s[2].append(int(x[1]))
	elif x[0] == '01':
		s[1].append(int(x[1]))
	else:
		s[0].append(int(x[1]))
ans = 0
for i in range(len(s[3])):
	ans = ans + s[3][i]
s[2] = sorted(s[2], reverse=True)
s[1] = sorted(s[1], reverse=True)
tlen = min(len(s[1]), len(s[2]))
for i in range(1, 3):
	for j in range(tlen):
		ans = ans + s[i][j]
	for j in range(tlen, len(s[i])):
		s[0].append(s[i][j])
s[0] = sorted(s[0], reverse=True)
tlen = min(len(s[3]), len(s[0]))
for i in range(tlen):
	ans = ans + s[0][i]
print(ans)


n = int(input())
lis10 = []
lis01 = []
lis00 = []
inf = c11 = c10 = c01 = c = c00 = 0
for i in range(n):
	(a, b) = list(map(str, input().split()))
	if a == '11':
		inf += int(b)
		c11 += 1
	elif a == '10':
		c10 += 1
		lis10.append(int(b))
	elif a == '01':
		c01 += 1
		lis01.append(int(b))
	else:
		c00 += 1
		lis00.append(int(b))
lis10.sort(reverse=True)
lis01.sort(reverse=True)
c = min(c01, c10)
for i in range(c):
	inf += lis10[i] + lis01[i]
lis00 += lis10[c:c10] + lis01[c:c01]
lis00.sort(reverse=True)
for i in range(min(c11, len(lis00))):
	inf += lis00[i]
print(inf)


arr = [[], [], []]
ans = 0
temp = 0
for _ in range(int(input())):
	(s, c) = input().split()
	if s == '11':
		ans += int(c)
		temp += 1
	elif s == '00':
		arr[0].append(int(c))
	elif s == '01':
		arr[1].append(int(c))
	else:
		arr[2].append(int(c))
temp1 = min(len(arr[1]), len(arr[2]))
arr[1].sort(reverse=True)
arr[2].sort(reverse=True)
for i in range(temp1):
	ans += arr[1][i] + arr[2][i]
if len(arr[1]) < len(arr[2]):
	for i in range(temp1, len(arr[2])):
		arr[0].append(arr[2][i])
else:
	for i in range(temp1, len(arr[1])):
		arr[0].append(arr[1][i])
arr[0].sort(reverse=True)
temp3 = min(temp, len(arr[0]))
for i in range(temp3):
	ans += arr[0][i]
print(ans)


n = int(input())
influences = [[], [], [], []]
for i in range(0, n):
	[support, influence] = [x for x in input().split()]
	support = int(support, 2)
	influences[support].append(int(influence))
for i in range(0, 4):
	influences[i] = sorted(influences[i])
	influences[i].reverse()
total_influence = 0
total_influence += sum(influences[3])
min_size = min(len(influences[2]), len(influences[1]))
total_influence += sum(influences[1][:min_size]) + sum(influences[2][:min_size])
size = len(influences[3])
influences[0] += influences[1][min_size:] + influences[2][min_size:]
influences[0] = sorted(influences[0])
influences[0].reverse()
total_influence += sum(influences[0][:size])
print(total_influence)


n = int(input())
su0 = []
su1 = []
su00 = []
su11 = []
ans = 0
for i in range(n):
	(sup, val) = map(int, input().split())
	if sup == 0:
		su00.append(val)
	elif sup == 11:
		su11.append(val)
	elif sup == 1:
		su0.append(val)
	else:
		su1.append(val)
su0.sort()
su1.sort()
su11.sort()
su00.sort()
while len(su1) != 0 and len(su0) != 0:
	ans += su1[len(su1) - 1] + su0[len(su0) - 1]
	su1.pop()
	su0.pop()
while len(su11) != 0 and len(su00) != 0:
	if len(su1) != 0:
		k = 1
	elif len(su0) != 0:
		k = 0
	else:
		k = 2
	if k == 0:
		if su00[len(su00) - 1] > su0[len(su0) - 1]:
			ans += su11[len(su11) - 1] + su00[len(su00) - 1]
			su11.pop()
			su00.pop()
		else:
			ans += su11[len(su11) - 1] + su0[len(su0) - 1]
			su11.pop()
			su0.pop()
	elif k == 1:
		if su00[len(su00) - 1] > su1[len(su1) - 1]:
			ans += su11[len(su11) - 1] + su00[len(su00) - 1]
			su11.pop()
			su00.pop()
		else:
			ans += su11[len(su11) - 1] + su1[len(su1) - 1]
			su11.pop()
			su1.pop()
	else:
		ans += su11[len(su11) - 1] + su00[len(su00) - 1]
		su11.pop()
		su00.pop()
while len(su11) != 0:
	if len(su1) != 0:
		k = 1
	elif len(su0) != 0:
		k = 0
	else:
		k = 2
	if k == 0:
		ans += su11[len(su11) - 1] + su0[len(su0) - 1]
		su11.pop()
		su0.pop()
	elif k == 1:
		ans += su11[len(su11) - 1] + su1[len(su1) - 1]
		su11.pop()
		su1.pop()
	else:
		ans += su11[len(su11) - 1]
		su11.pop()
print(ans)


def __starting_point():
	n = int(input())
	supporters = {}
	supporters[0] = []
	supporters[1] = []
	supporters[10] = []
	supporters[11] = []
	for i in range(n):
		[x, y] = [int(x) for x in input().split()]
		supporters[x].append(y)
	for x in supporters:
		supporters[x].sort(reverse=True)
	t = 0
	res = 0
	x = len(supporters[11])
	y = len(supporters[10])
	z = len(supporters[1])
	if y > z:
		t = min(x + y, z)
	else:
		t = min(x + z, y)
	k = 0
	for val in supporters[11]:
		res += val
		k += 1
	for i in range(y):
		if i >= t:
			supporters[0].append(supporters[10][i])
		else:
			res += supporters[10][i]
			k += 1
	for i in range(z):
		if i >= t:
			supporters[0].append(supporters[1][i])
		else:
			res += supporters[1][i]
			k += 1
	supporters[0].sort(reverse=True)
	t = min(x + y, x + z)
	i = 0
	while 2 * t > k and i < len(supporters[0]):
		k += 1
		res += supporters[0][i]
		i += 1
	print(res)
__starting_point()


from collections import defaultdict
c = defaultdict(int)
m = defaultdict(list)
n = int(input())
for i in range(n):
	(s, a) = input().split()
	m[s].append(int(a))
	c[s] += 1
ali = c['10']
bob = c['01']
co = c['11']
no = c['00']
if (ali == 0 or bob == 0) and co == 0:
	print(0)
else:
	if ali > bob:
		ali -= ali - bob
	else:
		bob -= bob - ali
	x = m['10']
	y = m['01']
	x.sort(reverse=True)
	y.sort(reverse=True)
	ans = sum(x[:ali]) + sum(y[:ali])
	rem = x[ali:] + y[ali:] + m['00']
	tot = ali + bob
	if co > 0:
		ans += sum(m['11'])
		tot += co
		ali += co
		bob += co
	rem.sort(reverse=True)
	mn = min(ali, bob)
	re = max(2 * mn - tot, 0)
	ans += sum(rem[:re])
	print(ans)


n = int(input())
both = []
a = []
b = []
neither = []
for i in range(n):
	(c, d) = map(int, input().split())
	if c == 11:
		both.append(d)
	elif c == 10:
		a.append(d)
	elif c == 1:
		b.append(d)
	else:
		neither.append(d)
inf = sum(both)
lee = len(both)
a.sort(reverse=True)
b.sort(reverse=True)
x = min(len(a), len(b))
inf += sum(a[:x]) + sum(b[:x])
neither += a[x:] + b[x:]
neither.sort(reverse=True)
if len(neither) < lee:
	inf += sum(neither)
else:
	inf += sum(neither[:lee])
print(inf)


n = int(input())
tonumber = {'00': 0, '01': 1, '10': 2, '11': 3}
people = [[], [], [], []]
for i in range(n):
	(s, a) = input().split()
	(s, a) = (tonumber[s], int(a))
	people[s].append(a)
people[0].sort(reverse=True)
people[1].sort(reverse=True)
people[2].sort(reverse=True)
totalInfluence = sum(people[3])
totalPeople = len(people[3])
support = [len(people[3]), len(people[3])]
minLen = min(len(people[1]), len(people[2]))
for i in range(minLen):
	totalInfluence += people[1][i] + people[2][i]
	totalPeople += 2
	support[0] += 1
	support[1] += 1
longer = 0
longerIndex = 2
if minLen == len(people[1]):
	longer = 0
	longerIndex = 2
else:
	longer = 1
	longerIndex = 1
indices = [0, minLen]
allEmpty = [len(people[0]), len(people[longerIndex])]
while indices != allEmpty:
	top = [-1, -1]
	if indices[0] != allEmpty[0]:
		top[0] = people[0][indices[0]]
	if indices[1] != allEmpty[1]:
		top[1] = people[longerIndex][indices[1]]
	if top[0] > top[1]:
		if support[longer] >= (totalPeople + 1) / 2 and support[not longer] >= (totalPeople + 1) / 2:
			totalInfluence += top[0]
			totalPeople += 1
			indices[0] += 1
		else:
			indices[0] += 1
	elif support[not longer] >= (totalPeople + 1) / 2:
		totalInfluence += top[1]
		totalPeople += 1
		support[longer] += 1
		indices[1] += 1
	else:
		indices[1] += 1
if totalPeople != 0:
	print(totalInfluence)
else:
	print(0)


import sys
a = []
b = []
c = []
d = []

def main():
	n = int(sys.stdin.readline().strip('\n'))
	for i in range(n):
		(opt, num) = [int(line) for line in sys.stdin.readline().strip('\n').split()[:2]]
		if opt == 0:
			a.append(num)
		if opt == 10:
			b.append(num)
		if opt == 1:
			c.append(num)
		if opt == 11:
			d.append(num)
	res = sum(d)
	b.sort(reverse=True)
	c.sort(reverse=True)
	if len(b) > len(c):
		res += sum(c) + sum(b[:len(c)])
		a.extend(b[len(c):])
	else:
		res += sum(b) + sum(c[:len(b)])
		a.extend(c[len(b):])
	a.sort(reverse=True)
	res += sum(a[:len(d)])
	print(res)

def __starting_point():
	main()
__starting_point()


n = int(input())
a10 = []
a01 = []
a00 = []
cnt11 = 0
cnt10 = 0
cnt01 = 0
cnt00 = 0
res = 0
for i in range(n):
	(t1, t2) = input().split(' ')
	if t1 == '11':
		cnt11 += 1
		res += int(t2)
	elif t1 == '10':
		cnt10 += 1
		a10.append(int(t2))
	elif t1 == '01':
		cnt01 += 1
		a01.append(int(t2))
	else:
		cnt00 += 1
		a00.append(int(t2))
cnt = min(cnt01, cnt10)
a01 = sorted(a01, reverse=True)
a10 = sorted(a10, reverse=True)
for i in range(cnt):
	res += a01[i]
	res += a10[i]
if cnt10 > cnt01:
	a00 += a10[cnt:]
elif cnt01 > cnt10:
	a00 += a01[cnt:]
a00 = sorted(a00, reverse=True)
for i in range(min(cnt11, len(a00))):
	res += a00[i]
print(res)


n = int(input())
a = []
b = []
c = []
d = []
for i in range(n):
	(opt, num) = [int(x) for x in input().split()]
	if opt == 0:
		a.append(num)
	if opt == 10:
		b.append(num)
	if opt == 1:
		c.append(num)
	if opt == 11:
		d.append(num)
ans = sum(d)
b.sort(reverse=True)
c.sort(reverse=True)
if len(b) < len(c):
	ans += sum(b) + sum(c[0:len(b)])
	a.extend(c[len(b):])
else:
	ans += sum(c) + sum(b[0:len(c)])
	a.extend(b[len(c):])
a.sort(reverse=True)
ans += sum(a[0:len(d)])
print(ans)


from collections import defaultdict
n = int(input())
a = defaultdict(list)
for i in range(n):
	(h, m) = list(map(int, input().split()))
	a[h].append(m)
k = sum(a[11])
a[10].sort()
a[1].sort()
a[0].sort()
g = 0
if len(a[1]) > len(a[10]):
	z = len(a[10])
	g = 1
else:
	g = 10
	z = len(a[1])
while z > 0:
	k += a[1].pop()
	k += a[10].pop()
	z -= 1
l = len(a[11])
while l > 0:
	if len(a[g]) > 0 and len(a[0]) > 0:
		if a[0][-1] > a[g][-1]:
			k += a[0].pop()
		else:
			k += a[g].pop()
	elif len(a[g]) > 0:
		k += a[g].pop()
	elif len(a[0]) > 0:
		k += a[0].pop()
	else:
		break
	l -= 1
print(k)


from math import *
n = int(input())
arr = []
count1 = 0
count2 = 0
ans = 0
for i in range(n):
	(a, b) = map(str, input().split())
	b = int(b)
	arr.append((b, a))
	if arr[i][1] == '10':
		count1 += 1
	elif arr[i][1] == '01':
		count2 += 1
	elif arr[i][1] == '11':
		count1 += 1
		count2 += 1
	ans += arr[i][0]
arr.sort(reverse=True)
i = n - 1
flag = 0
size = n
minval = min(count1, count2)
while i >= 0 and (count1 < ceil(size / 2) or count2 < ceil(size / 2)):
	if arr[i][1] == '00':
		ans -= arr[i][0]
		size -= 1
	elif arr[i][1] == '10':
		if count1 > minval:
			ans -= arr[i][0]
			count1 -= 1
			size -= 1
	elif arr[i][1] == '01':
		if count2 > minval:
			ans -= arr[i][0]
			count2 -= 1
			size -= 1
	i -= 1
if i == 0 and (count1 < ceil(size / 2) or count2 < ceil(size / 2)):
	print(0)
else:
	print(ans)


def read():
	return []

def main():
	n = int(input())
	d = [[], [], [], []]
	for _ in range(n):
		(key, influence) = input().split()
		key = int(key, 2)
		d[key].append(int(influence))
	for key in range(4):
		d[key].sort(reverse=True)
	ans = sum(d[3])
	additional = len(d[3])
	container = []
	if len(d[1]) < len(d[2]):
		container = d[2]
	elif len(d[1]) > len(d[2]):
		container = d[1]
	container_start = min(len(d[1]), len(d[2]))
	zeros_start = 0
	for (a1, a2) in zip(d[1], d[2]):
		ans += a1 + a2
	while (container_start < len(container) or zeros_start < len(d[0])) and additional:
		(t1, t2) = (0, 0)
		if container_start < len(container):
			t1 = container[container_start]
		if zeros_start < len(d[0]):
			t2 = d[0][zeros_start]
		if t1 < t2:
			ans += t2
			zeros_start += 1
		elif t1 >= t2 and t1 != 0:
			ans += t1
			container_start += 1
		additional -= 1
	print(ans)

def __starting_point():
	main()
__starting_point()


d = {'00': [], '01': [], '10': [], '11': []}
n = int(input())
for i in range(n):
	(x, p) = input().split()
	d[x].append(int(p))
for key in d.keys():
	d[key].sort(reverse=True)
t = '01' if len(d['01']) <= len(d['10']) else '10'
t1 = '01' if t == '10' else '10'
ans = 0
ans += sum(d['11']) + sum(d[t]) + sum(d[t1][:len(d[t])])
e = len(d['11'])
l1 = sorted(d[t1][len(d[t]):] + d['00'], reverse=True)
ans += sum(l1[:e])
print(ans)


from math import ceil
(n, A) = (int(input()), [])
a = b = ab = ab_ = ans = 0
for _ in range(n):
	(t, tt) = input().split()
	tt = int(tt)
	if t != '11':
		A.append([t, tt])
		if t == '10':
			a += 1
		elif t == '01':
			b += 1
		else:
			ab_ += 1
	else:
		ans += tt
		ab += 1
A.sort(reverse=True, key=lambda x: x[1])
x = y = t = ttt = ab
(k, j) = (a, b)
for i in A:
	if i[0] == '10' and (j or ttt):
		ans += i[1]
		t += 1
		x += 1
		if j == 0 and ttt:
			ttt -= 1
			j = 1
		j -= 1
	elif i[0] == '01' and (k or ttt):
		ans += i[1]
		t += 1
		y += 1
		if k == 0 and ttt:
			ttt -= 1
			k = 1
		k -= 1
	elif i[0] == '00' and ttt:
		ans += i[1]
		ttt -= 1
		t += 1
print(ans)


n = int(input())
(a, b, c) = ([], [], [])
ans = 0
num11 = 0
for i in range(n):
	(t, val) = map(int, input().split())
	if t == 11:
		ans += val
		num11 += 1
		continue
	if t & 1:
		a.append(val)
	if t & 2:
		b.append(val)
	if not t:
		c.append(val)
a.sort(reverse=True)
b.sort(reverse=True)
min_num = min(len(a), len(b))
ans += sum(a[:min_num]) + sum(b[:min_num])
t = a[min_num:] + b[min_num:] + c
t.sort(reverse=True)
ans += sum(t[:2 * (min(len(a), len(b)) + num11) - 2 * min_num - num11])
print(ans)


n = int(input())
a = [[] for i in range(4)]
for i in range(n):
	(s, influence) = [i for i in input().split()]
	a[int(s, 2)].append(int(influence))
for i in range(4):
	a[i].sort(reverse=True)

def check():
	x = len(a[1])
	y = len(a[2])
	xy = len(a[3])
	z = len(a[0])
	if xy + y == 0 or xy + x == 0:
		print(0)
		return
	w = min(x, y)
	sum0 = 0
	sum0 += sum(a[1][:w]) + sum(a[2][:w]) + sum(a[3])
	choose = 2
	if x >= y:
		choose = 1
	num = 0
	i = w
	j = 0
	while i < max(x, y) and j < z and (num < xy):
		if a[choose][i] >= a[0][j]:
			sum0 += a[choose][i]
			i += 1
		else:
			sum0 += a[0][j]
			j += 1
		num += 1
	while i < max(x, y) and num < xy:
		sum0 += a[choose][i]
		i += 1
		num += 1
	while j < z and num < xy:
		sum0 += a[0][j]
		j += 1
		num += 1
	print(sum0)
check()


import math
n = int(input())
d = {}
d['00'] = []
d['01'] = []
d['10'] = []
d['11'] = []
count = {'00': 0, '01': 0, '10': 0, '11': 0}
ans = 0
length = 0
if n == 1:
	(x, y) = input().split()
	if x == '00':
		print(0)
	elif x == '11':
		print(int(y))
	else:
		print(0)
else:
	for i in range(n):
		(x, y) = input().split()
		d[x].append(int(y))
	l1 = d['00']
	l2 = d['01']
	l3 = d['10']
	l4 = d['11']
	(l1, l2, l3, l4) = (sorted(l1), sorted(l2), sorted(l3), sorted(l4))
	j = len(l4) - 1
	while j >= 0:
		ans += l4[j]
		j -= 1
		count['11'] += 1
	(c1, c4) = (len(l1) - 1, -1)
	i = len(l2) - 1
	j = len(l3) - 1
	if len(l2) > 0 and len(l3) > 0:
		while i >= 0 and j >= 0:
			ans += l2[i]
			ans += l3[j]
			count['10'] += 1
			count['01'] += 1
			length += 2
			i -= 1
			j -= 1
		(c2, c3) = (i, j)
	else:
		(c2, c3) = (len(l2) - 1, len(l3) - 1)
	t = count['00'] + count['01'] + count['10'] + count['11']
	t1 = count['11'] + count['10']
	t2 = count['11'] + count['01']
	while t1 > math.ceil(t // 2) and t2 > math.ceil(t // 2):
		if c3 < 0:
			if c2 >= 0 and c1 >= 0:
				if l2[c2] > l1[c1]:
					t += 1
					ans += l2[c2]
					c2 -= 1
					count['01'] += 1
				else:
					t += 1
					ans += l1[c1]
					c1 -= 1
			else:
				if t1 > math.ceil(t // 2) and t2 > math.ceil(t // 2):
					if c2 >= 0:
						ans += l2[c2]
						c2 -= 1
						t += 1
						count['01'] += 1
				if t1 > math.ceil(t // 2) and t2 > math.ceil(t // 2):
					if c1 >= 0:
						t += 1
						ans += l1[c1]
						c1 -= 1
			if c2 < 0 and c1 < 0:
				break
		elif c2 < 0:
			if c3 >= 0 and c1 >= 0:
				if l3[c3] > l1[c1]:
					t += 1
					ans += l3[c3]
					c3 -= 1
					count['10'] += 1
				else:
					t += 1
					ans += l1[c1]
					c1 -= 1
			else:
				if t1 > math.ceil(t // 2) and t2 > math.ceil(t // 2):
					if c3 >= 0:
						ans += l3[c3]
						c3 -= 1
						t += 1
						count['10'] += 1
				if t1 > math.ceil(t // 2) and t2 > math.ceil(t // 2):
					if c1 >= 0:
						t += 1
						ans += l1[c1]
						c1 -= 1
			if c3 < 0 and c1 < 0:
				break
		t1 = count['11'] + count['10']
		t2 = count['11'] + count['01']
	print(ans)


def fun(c):
	return c[0]

def f(a, b, alice, bob, un, n, check):
	inf = 0
	if n - a <= a:
		inf = 0
		for i in range(n):
			inf += int(inp[i][1])
	else:
		tempb = 0
		j = 0
		for i in range(a):
			inf += alice[i][0]
			d[alice[i][1]] = 1
			if who[alice[i][1]][check] == '1':
				tempb += 1
			j += 1
		i = 0
		while i < b and tempb < a:
			if d[bob[i][1]] == 0:
				inf += bob[i][0]
				tempb += 1
				j += 1
			i += 1
		if j < 2 * a:
			k = 0
			unn = len(un)
			while j < 2 * a and i < b and (k < unn):
				if i < b and k < unn:
					if d[bob[i][1]] == 1:
						i += 1
					elif bob[i][0] > un[k][0]:
						inf += bob[i][0]
						i += 1
						j += 1
					else:
						inf += un[k][0]
						k += 1
						j += 1
			while j < 2 * a and i < b:
				if d[bob[i][1]] == 1:
					i += 1
				else:
					inf += bob[i][0]
					i += 1
					j += 1
			while j < 2 * a and k < unn:
				inf += un[k][0]
				k += 1
				j += 1
	print(inf)
n = int(input())
d = {}
who = {}
inp = []
a = 0
b = 0
alice = []
bob = []
un = []
for i in range(n):
	t = input().split()
	if t[0][0] == '1':
		a += 1
		temp = [int(t[1]), i]
		d[i] = 0
		alice.append(temp)
	if t[0][1] == '1':
		b += 1
		temp = [int(t[1]), i]
		bob.append(temp)
		d[i] = 0
	if t[0][1] == t[0][0] and t[0][0] == '0':
		temp = [int(t[1]), i]
		un.append(temp)
	who[i] = t[0]
	inp.append(t)
alice.sort(key=fun, reverse=True)
bob.sort(key=fun, reverse=True)
un.sort(key=fun, reverse=True)
inf = 0
if a < b:
	f(a, b, alice, bob, un, n, 1)
else:
	f(b, a, bob, alice, un, n, 0)


n = int(input())
both = []
(a, b) = ([], [])
no = []
lb = 0
la = 0
for _ in range(n):
	(x, y) = [x for x in input().split()]
	if x == '11':
		both.append(int(y))
	elif x == '01':
		b.append(int(y))
		lb += 1
	elif x == '10':
		a.append(int(y))
		la += 1
	else:
		no.append(int(y))
a.sort(reverse=True)
b.sort(reverse=True)
ans = sum(both)
mini = min(la, lb)
ans2 = 0
for i in range(mini):
	ans += a[i] + b[i]
if la > lb:
	for i in range(mini, la):
		no.append(a[i])
else:
	for i in range(mini, lb):
		no.append(b[i])
temp = min(len(both), len(no))
no.sort(reverse=True)
for i in range(temp):
	ans += no[i]
print(ans)


import collections
import sys
import traceback

class Input(object):

	def __init__(self):
		self.fh = sys.stdin

	def next_line(self):
		while True:
			line = sys.stdin.readline()
			if line == '\n':
				continue
			return line

	def next_line_ints(self):
		line = self.next_line()
		return [int(x) for x in line.split()]

	def next_line_strs(self):
		line = self.next_line()
		return line.split()

def get_max_influence(influence):
	for i in range(4):
		influence[i].sort(reverse=True)
	t = [0] * 4
	result = 0
	while t[1] < len(influence[1]) and t[2] < len(influence[2]):
		result += influence[1][t[1]] + influence[2][t[2]]
		t[1] += 1
		t[2] += 1
	while t[3] < len(influence[3]):
		best = 0
		best_id = -1
		for i in range(3):
			if t[i] < len(influence[i]) and influence[i][t[i]] > best:
				best = influence[i][t[i]]
				best_id = i
		result += influence[3][t[3]]
		t[3] += 1
		if best_id != -1:
			result += influence[best_id][t[best_id]]
			t[best_id] += 1
	return result

def main():
	input = Input()
	while True:
		try:
			nums = input.next_line_ints()
			if not nums:
				break
			(n,) = nums
			if n == -1:
				break
			influence = [[] for _ in range(4)]
			for _ in range(n):
				(support, value) = input.next_line_strs()
				influence[int(support, 2)].append(int(value))
		except:
			print('read input failed')
		try:
			max_value = get_max_influence(influence)
			print('{}'.format(max_value))
		except:
			traceback.print_exc(file=sys.stdout)
			print('get_min_dist failed')
main()


n = int(input())
x_s = []
y_s = []
w_s = []
z_s = []
for _ in range(n):
	(s, a) = input().split(' ')
	a = int(a)
	if s == '00':
		z_s.append(a)
	if s == '01':
		x_s.append(a)
	if s == '10':
		y_s.append(a)
	if s == '11':
		w_s.append(a)
w_s = list(reversed(sorted(w_s)))
x_s = list(reversed(sorted(x_s)))
y_s = list(reversed(sorted(y_s)))
z_s = list(reversed(sorted(z_s)))
if len(x_s) > len(y_s):
	tmp = y_s
	y_s = x_s
	x_s = tmp
if len(w_s) == 0 and (len(x_s) == 0 or len(y_s) == 0):
	print(0)
else:
	base_influence = sum(w_s) + sum(x_s) + sum(y_s[:len(x_s)])
	best_influence = 0
	w = len(w_s)
	y_s = y_s[len(x_s):]
	z_prefix_sums = []
	z_sum = 0
	for z in z_s:
		z_sum += z
		z_prefix_sums.append(z_sum)
	y_sum = 0
	for y in range(len(y_s) + 1):
		if y > 0:
			y_sum += y_s[y - 1]
		z = w - y
		if z >= 0:
			this_influence = base_influence + y_sum
			if z_s and z > 0:
				this_influence += z_prefix_sums[min(z - 1, len(z_prefix_sums) - 1)]
			best_influence = max(best_influence, this_influence)
	print(best_influence)


n = int(input())
a = []
b = []
c = []
d = []
for i in range(n):
	(e, f) = list(map(int, input().split()))
	if e == 11:
		a.append(f)
	elif e == 10:
		b.append(f)
	elif e == 1:
		c.append(f)
	elif e == 0:
		d.append(f)
a.sort(reverse=True)
b.sort(reverse=True)
c.sort(reverse=True)
d.sort(reverse=True)
e = min(len(c), len(b))
f = a + b[:e] + c[:e]
g = d + b[e:] + c[e:]
g.sort(reverse=True)
g = g[:len(a)]
print(sum(f) + sum(g))


import traceback
import math
from collections import defaultdict
from functools import lru_cache
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 geti():
	return int(input())

def gets():
	return input()

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

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

def get2d(nrows, ncols, n=0):
	return [[n] * ncols for r in range(nrows)]
ceil = lambda x: int(math.ceil(x))
inf = float('inf')
mod = 10 ** 9 + 7

def main():
	N = geti()
	g = defaultdict(list)
	for _ in range(N):
		(x, n) = getsl()
		g[x].append(int(n))
	for x in g:
		g[x].sort(reverse=True)
	ans = sum(g['11'])
	c = len(g['11'])
	sz = min(len(g['10']), len(g['01']))
	ans += sum(g['10'][:sz]) + sum(g['01'][:sz])
	g['00'].extend(g['10'][sz:] + g['01'][sz:])
	g['00'].sort(reverse=True)
	ans += sum(g['00'][:c])
	return ans
try:
	ans = main()
	print(ans)
except Exception as e:
	traceback.print_exc()