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: competition

Starter code:

Solutions:
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=0
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)

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

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

def num():
	return list(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)


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:
		#print("alice")
		#print(*alice)
		#print("bob")
		#print(*bob);
		#print("un")
		#print(*un)

		#print("H")
		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;
		#print("inf",inf,"j",j,"tempb",tempb)
		#print("d",d)
		while(i<b and tempb < a):
			if d[bob[i][1]]==0:
				#(bob[i])
				inf+=bob[i][0];
				tempb+=1
				j+=1;
			i+=1;
		#print(inf,j)
		if j < 2*a:
			k = 0;
			unn = len(un);
			#print(i)
			while( j < 2*a and i < b and k < unn):
				if ( i < b and k <unn):
					if (d[bob[i][1]]==1):
						i+=1;
					else:
						#print(bob[i][0],un[k][0])
						if (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);
#print(*alice);
#print(*bob);
#print(*un)
inf = 0;

if a < b:
	f(a,b,alice,bob,un,n,1);
else:
	#print("YO")
	f(b,a,bob,alice,un,n,0);









n=int(input())
su0=[]
su1=[]
su00=[]
su11=[]
ans=0
for i in range(n):
	sup,val=map(int,input().split())
	if(sup==00):
		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)

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
    #print(size,count1,count2,ans)
    i-=1
if(i==0 and (count1<ceil(size/2) or count2<ceil(size/2))):
    print(0)
else:
    print(ans)


n = int(input())
#00 = 0, 01 = 1, 10 = 2, 11 = 3
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)
#print(people)
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])]
#print(longer, longerIndex, minLen, indices, allEmpty)
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:
            #print(str(support[longer]) + ' ' +  str((totalPeople + 1) / 2) + ';' + str(support[not longer]) + ' ' +  str((totalPeople + 1) / 2))
            totalInfluence += top[0]
            totalPeople += 1
            indices[0] += 1
        else:
            indices[0] += 1
    else:
        if support[not longer] >= (totalPeople + 1) / 2:
            totalInfluence += top[1]
            totalPeople += 1
            support[longer] += 1
            indices[1] += 1
        else:
            indices[1] += 1
    #print(top, support, totalInfluence, totalPeople)

if totalPeople != 0:
    print(totalInfluence)
else:
    print(0)


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=[[] 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()






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
    #print(ali,bob,tot)
    rem.sort(reverse=True)
    #print(rem)
    mn = min(ali,bob)
    re = max(2*mn-tot,0)
    #print(re)
    ans+=sum(rem[:re])
    print(ans)
    


#!/usr/bin/env python3

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)
        #print('influence[{}] = {}'.format(i, influence[i]))
    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))
                #print('influence = {}'.format(influence))
        except:
            print('read input failed')
        try:
            #print('influence = {}'.format(influence))
            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())
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)

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)
        #print(x,y)

    for x in supporters:
        supporters[x].sort(reverse=True)
        #print(supporters[x])

    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
    #print(res)
    while 2*t > k and i<len(supporters[0]):
        k+=1
        #print(supporters[0][i])
        res += supporters[0][i]
        i+=1

    print(res)     

__starting_point()

#!usr/bin/python

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









# -*- coding:utf-8 -*-

"""

created by shuangquan.huang at 11/3/18

"""



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)
    
    
# all people '11' supports both will be selected
ans = sum(A[3] or [0])

# select equal number of '01' or '10'

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
# select left '01' '10' or '00' make total people <= 2*x, current have 2*single + len(A[3])
# so at most select len(A[3]) more people

a = A[1][single:] + A[2][single:] + A[0]
a.sort(reverse=True)
ans += sum(a[: len(A[3])] or [0])

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

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)
else:
    if 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)

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=0
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)

import sys

a = []
b = []
c = []
d = []

def main():
	#sys.stdin = open('D:\\Sublime\\in.txt', 'r')
	#sys.stdout = open('D:\\Sublime\\out.txt', 'w')

	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())
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) # from the largest then choose: greedy
c.sort(reverse=True) # make sortings is O(nlogn)
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)

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)

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)

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())
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)
#if len(lis00)<c11:
#    print(inf)
#else:    
for i in range(min(c11,len(lis00))):
    inf+=lis00[i]
print(inf)    


# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
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)
    
#print(f)

s_X = sum(f['11'])
# X >= W
X = len(f['11'])
Y = len(f['10'])
Z = len(f['01'])

m = min(Y,Z)

# calculate prefix of '10' and '01'
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

# W = 0 to X
res = 0
s = 0
for W in range(X+1):
    # abs(Y-Z) <= X-W
    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)
    
    # X+W+Y+Z
    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(X,tmp_Y,tmp_Z,W,calculate)
    
print(res)
            


    


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)