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.

Difficulty: MEDIUM

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)


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)


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)


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()