Marcin is a coach in his university. There are $n$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.

Let's focus on the students. They are indexed with integers from $1$ to $n$. Each of them can be described with two integers $a_i$ and $b_i$; $b_i$ is equal to the skill level of the $i$-th student (the higher, the better). Also, there are $60$ known algorithms, which are numbered with integers from $0$ to $59$. If the $i$-th student knows the $j$-th algorithm, then the $j$-th bit ($2^j$) is set in the binary representation of $a_i$. Otherwise, this bit is not set.

Student $x$ thinks that he is better than student $y$ if and only if $x$ knows some algorithm which $y$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.

Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?


-----Input-----

The first line contains one integer $n$ ($1 \leq n \leq 7000$) — the number of students interested in the camp.

The second line contains $n$ integers. The $i$-th of them is $a_i$ ($0 \leq a_i < 2^{60}$).

The third line contains $n$ integers. The $i$-th of them is $b_i$ ($1 \leq b_i \leq 10^9$).


-----Output-----

Output one integer which denotes the maximum sum of $b_i$ over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.


-----Examples-----
Input
4
3 2 3 6
2 8 5 10

Output
15

Input
3
1 2 3
1 2 3

Output
0

Input
1
0
1

Output
0



-----Note-----

In the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of $b_i$.

In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset.

Difficulty: MEDIUM_HARD
Tags: Complete search

Greedy algorithms
Skill types: Complete search

Greedy algorithms

Starter code:

Solutions:
from collections import Counter

def main():
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	rv = 0
	nums = {}
	for i in range(len(a)):
		if a[i] not in nums:
			nums[a[i]] = []
		nums[a[i]].append(i)
	visited = set()
	for num in nums:
		if len(nums[num]) > 1:
			i = nums[num][0]
			j = nums[num][1]
			if i not in visited:
				visited.add(i)
				rv += b[i]
			if j not in visited:
				visited.add(j)
				rv += b[j]
			for k in range(len(a)):
				if k in visited:
					continue
				if a[i] | a[k] == a[i]:
					visited.add(k)
					rv += b[k]
	return rv
print(main())


from collections import defaultdict
n = int(input())
aa = list(map(int, input().split()))
bb = list(map(int, input().split()))
d = {}
dd = defaultdict(set)
for i in range(n):
	a = aa[i]
	dd[a].add(i)
children = defaultdict(set)
for a in dd:
	for b in dd:
		if a | b == a:
			children[a] |= dd[b]
res = set()
for a in dd:
	sm = 0
	if len(dd[a]) >= 2:
		res |= children[a]
sm = 0
for i in res:
	sm += bb[i]
print(sm)


import collections
import time
import os
import sys
import bisect
import heapq
from typing import List

def issub(u, v):
	if u > v:
		return False
	if u == v:
		return True
	b = 1
	for i in range(v.bit_length() + 1):
		if v & b < u & b:
			return False
		b <<= 1
	return True

def solve(N, A, B):
	vi = collections.defaultdict(list)
	for (i, v) in enumerate(A):
		vi[v].append(i)
	wc = collections.Counter(A)
	group = {k for (k, v) in wc.items() if v > 1}
	others = {u for u in wc.keys() if u not in group and any((issub(u, v) for v in group))}
	group |= others
	ans = 0
	for u in group:
		ans += sum([B[i] for i in vi[u]])
	return ans
N = int(input())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
print(solve(N, A, B))


from collections import defaultdict
N = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
Total = 0
Dict = defaultdict(list)
for i in range(N):
	Dict[a[i]].append(b[i])
Total = 0
Visited = defaultdict(bool)
Selected = []
for i in Dict.keys():
	if len(Dict[i]) > 1:
		Total += sum(Dict[i])
		Selected.append(i)
		Visited[i] = True
for i in range(N):
	if Visited[a[i]] == False:
		for j in range(len(Selected)):
			if Selected[j] | a[i] == Selected[j]:
				Total += b[i]
				Visited[a[i]] = True
				break
print(Total)


def less_exp(a1, a2):
	return a1 < a2 and a2 - a1 == a1 ^ a2
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
g = []
for i in range(len(a)):
	g.append((a[i], b[i]))
g.sort(key=lambda x: x[0])
selected_nodes = set()
sum1 = 0
for i in range(len(a)):
	if i < len(a) - 1 and g[i][0] == g[i + 1][0]:
		selected_nodes.add(g[i][0])
		sum1 += g[i][1]
	elif i > 0 and (i == len(a) - 1 or g[i][0] != g[i + 1][0]) and (g[i][0] == g[i - 1][0]):
		sum1 += g[i][1]
if sum1 > 0:
	for node in g:
		if node[0] not in selected_nodes:
			for node1 in selected_nodes:
				if less_exp(node[0], node1):
					sum1 += node[1]
					break
print(sum1)


def bit(used, b):
	count = 0
	for num in used:
		for i in range(b.bit_length() + 1):
			if 1 << i & num == 0 and 1 << i & b:
				count += 1
				break
	if count == len(used):
		return True
	else:
		return False

def f(a, b):
	arr = list(zip(a, b))
	d = {}
	for i in arr:
		d[i[0]] = d.get(i[0], []) + [i[1]]
	cmax = -1
	ans = 0
	used = set()
	for i in d:
		if len(d[i]) >= 2:
			ans += sum(d[i])
			cmax = max(cmax, i)
			used.add(i)
	for i in d:
		if i in used:
			continue
		if bit(used, i) == True:
			continue
		else:
			ans += sum(d[i])
	return ans
a = input()
l = list(map(int, input().strip().split()))
l2 = list(map(int, input().strip().split()))
print(f(l, l2))


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 factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

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

def main():
	n = N()
	arra = RLL()
	arrb = RLL()
	dic = defaultdict(int)
	for i in arra:
		dic[i] += 1
	carr = set()

	def c(num):
		for i in range(n):
			if arra[i] | num == num:
				carr.add(i)
	res = 0
	for i in dic:
		if dic[i] > 1:
			c(i)
	for i in carr:
		res += arrb[i]
	print(res)
main()


n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
aSet = set()
duplicates = set()
for ai in a:
	if ai in aSet:
		duplicates.add(ai)
	aSet.add(ai)
total = 0
for (i, ai) in enumerate(a):
	if ai in duplicates:
		total += b[i]
		continue
	for d in duplicates:
		if ai & d == ai:
			total += b[i]
			break
print(total)


n = int(input())
a = [*map(int, input().split())]
b = [*map(int, input().split())]
from collections import Counter
c = Counter(a)
ans = 0
s = set()
d = {}
for i in range(n):
	d[a[i]] = d.get(a[i], 0) + b[i]
d = [*d.items()]
d.sort()
for (i, j) in d:
	if c[i] == 1:
		continue
	for (x, y) in d:
		if x > i:
			break
		if x & i == x and x not in s:
			ans += y
			s.add(x)
print(ans)


from collections import Counter

def main():
	n = int(input())
	a = readIntArr()
	b = readIntArr()
	cnts = Counter(a)
	ans = 0
	group = set()
	for i in range(n):
		if cnts[a[i]] >= 2:
			group.add(a[i])
			ans += b[i]
	for i in range(n):
		if cnts[a[i]] == 1:
			for possibleParent in group:
				if possibleParent | a[i] == possibleParent:
					ans += b[i]
					break
	print(ans)
	return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

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

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(i, j):
	print('? {} {}'.format(i, j))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(' '.join([str(x) for x in ans])))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
for _abc in range(1):
	main()


from collections import defaultdict
N = int(input())
if N == 1:
	print(0)
	exit()
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
Dict = defaultdict(int)
Sum = defaultdict(int)
for i in range(N):
	Dict[a[i]] += 1
	Sum[a[i]] += b[i]
ans = 0
val = 0
Group = []
for i in Dict.keys():
	if Dict[i] > 1:
		Group.append(i)
		ans += Sum[i]
		val |= i
for i in range(N):
	if Dict[a[i]] == 1:
		for k in Group:
			if a[i] | k <= k:
				ans += Sum[a[i]]
				break
print(ans)


n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
dict = {}
for a in A:
	if a in dict:
		dict[a] += 1
	else:
		dict[a] = 1
res = 0
group = []
for k in dict:
	if dict[k] > 1:
		group.append(k)
for i in range(n):
	for k in group:
		if A[i] | k == k:
			res += B[i]
			break
print(res)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
di = {}
for x in a:
	if x in di:
		di[x] += 1
	if x not in di:
		di[x] = 1
ans = 0
gb = []
for k in di:
	if di[k] > 1:
		gb.append(k)
for i in range(n):
	if di[a[i]] > 1:
		ans += b[i]
		continue
	for y in gb:
		if a[i] & y == a[i]:
			ans += b[i]
			break
print(ans)


n = int(input())
a = [0] * n
b = [0] * n
a = list(map(int, input().split(' ')))
b = list(map(int, input().split(' ')))
for i in range(n):
	a[i] = [a[i], b[i]]
a.sort(reverse=True, key=lambda x: x[0])
same = []
comp = a[0][0]
count = 1
score = a[0][1]
for i in range(1, n):
	if comp == a[i][0] and i == n - 1:
		count += 1
		score += a[i][1]
		same.append([comp, score, i])
	elif comp == a[i][0]:
		count += 1
		score += a[i][1]
	elif count > 1:
		same.append([comp, score, i - 1])
		comp = a[i][0]
		score = a[i][1]
		count = 1
	else:
		comp = a[i][0]
		score = a[i][1]
		count = 1
relevant = []
if len(same) == 0:
	print(0)
else:
	f = same[0][0]
	fscore = same[0][1]
	findex = same[0][2]
	for i in range(1, len(same)):
		if f & same[i][0] != same[i][0]:
			relevant.append(same[i][0])
	for i in range(findex + 1, n):
		if f & a[i][0] == a[i][0]:
			fscore += a[i][1]
		else:
			for j in relevant:
				if a[i][0] & j == a[i][0]:
					fscore += a[i][1]
					break
	print(fscore)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
lis = []
d = {}
for i in a:
	if i in d:
		d[i] += 1
	else:
		d[i] = 1
ans = 0
for i in d:
	if d[i] > 1:
		lis.append(i)
for i in range(len(lis)):
	for j in range(n):
		if lis[i] == a[j]:
			ans += b[j]
for i in range(n):
	if d[a[i]] == 1:
		c = 0
		for j in range(len(lis)):
			if a[i] & lis[j] == a[i]:
				lis.append(a[i])
				ans += b[i]
				break
print(ans)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
d = {}
for i in a:
	if i in d:
		d[i] += 1
	if i not in d:
		d[i] = 1
rez = 0
g = []
for i in d:
	if d[i] > 1:
		g.append(i)
for i in range(n):
	if d[a[i]] > 1:
		rez += b[i]
		continue
	for y in g:
		if a[i] & y == a[i]:
			rez += b[i]
			break
print(rez)


from math import *
from collections import *
from bisect import *
import sys
input = sys.stdin.readline
t = 1
while t:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	g = {}
	for i in range(n):
		try:
			g[a[i]] += 1
		except:
			g[a[i]] = 1
	res = 0
	for i in range(n):
		for j in g.keys():
			if g[j] > 1:
				if a[i] | j == j:
					res += b[i]
					break
	print(res)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
d = {}
for i in a:
	if i in d:
		d[i] += 1
	else:
		d[i] = 1
g = []
re = 0
for i in d:
	if d[i] > 1:
		g.append(i)
for i in range(n):
	if d[a[i]] > 1:
		re += b[i]
		continue
	for y in g:
		if a[i] & y == a[i]:
			re += b[i]
			break
print(re)


import os
import sys
from io import BytesIO, IOBase
from collections import Counter

def main():
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	c = Counter(a)
	if len(c) == n:
		print(0)
	else:
		(d, e, ans, f) = (Counter(), [], 0, [])
		for (i, v) in enumerate(a):
			d[v] += b[i]
		for i in c:
			if c[i] > 1:
				f.append(i)
				ans += d[i]
			else:
				e.append([i, d[i]])
		for (i, j) in e:
			for x in f:
				if x | i == x:
					ans += j
					break
		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 = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
B = [(b, a) for (a, b) in zip(A, B)]
C = {}
for a in A:
	if a not in C:
		C[a] = 0
	C[a] += 1
inc = set()
for c in C:
	if C[c] > 1:
		inc.add(c)
ans = 0
for (b, a) in B:
	if a in inc:
		ans += b
	else:
		flag = False
		for c in inc:
			if c & a == a:
				flag = True
		if flag:
			ans += b
print(ans)


from collections import Counter
n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
c = Counter(a)
s = set()
for x in c:
	if c[x] > 1:
		s.add(x)
res = {x for x in s}
for x in a:
	if x not in s:
		for y in s:
			if y & x == x:
				res.add(x)
r = 0
for i in range(n):
	if a[i] in res:
		r += b[i]
print(r)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
v = []
for i in range(n):
	v.append([a[i], b[i]])
v.sort()
prev = -1
big = []
flag = True
for i in v:
	if prev == i[0] and (flag or big[-1] != i[0]):
		big.append(i[0])
		flag = False
	prev = i[0]
answer = 0
counter = 0
big.sort()
for i in v:
	for j in big:
		if j == j | i[0]:
			answer += i[1]
			counter += 1
			break
if counter < 2:
	print(0)
else:
	print(answer)


def is_subset(a, b):
	return ~a & b == 0
n = int(input())
a = map(int, input().split())
b = map(int, input().split())
vis = [False] * (n + 1)
st = list(zip(a, b))
st.sort()
st.reverse()
st.append((-1, -1))
ans = 0
for i in range(n):
	if st[i][0] != st[i + 1][0]:
		continue
	for j in range(i, n):
		if is_subset(st[i][0], st[j][0]):
			vis[j] = True
for i in range(n):
	ans += vis[i] * st[i][1]
print(ans)


from sys import *
n = int(stdin.readline())
a = list(map(int, stdin.readline().split()))
b = list(map(int, stdin.readline().split()))
gp = []
ans = []
for i in range(n):
	if a.count(a[i]) > 1:
		if a[i] not in gp:
			gp.append(a[i])
		ans.append(b[i])
if len(gp) == 0:
	stdout.write('0')
else:

	def better(a, gp):
		for i in range(len(gp)):
			if a | gp[i] == gp[i]:
				return False
		return True
	for i in range(n):
		if a[i] not in gp:
			if better(a[i], gp) == False:
				gp.append(a[i])
				ans.append(b[i])
	stdout.write(str(sum(ans)))


from collections import defaultdict
from collections import Counter
import sys
sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
D_A = defaultdict(int)
D_bin = {}
for a in A:
	D_bin[a] = format(a, 'b').zfill(60)
for (a, b) in zip(A, B):
	D_A[a] += b
C_A = Counter(A)
leader_cand = set()
for (n, v) in C_A.most_common():
	if v >= 2:
		leader_cand.add(n)
ans = 0
for (key, val) in D_A.items():
	if key in leader_cand:
		ans += D_A[key]
	else:
		key_bin = D_bin[key]
		for lead in leader_cand:
			c_bin = D_bin[lead]
			if all((s >= t for (s, t) in zip(c_bin, key_bin))):
				ans += D_A[key]
				break
print(ans)


import sys
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
if n == 1:
	print(0)
	sys.exit(0)
X = []
for i in range(n):
	X.append((A[i], B[i]))
X.sort()
Y = []
S = set()
ans = 0
for i in range(n):
	if i < n - 1 and X[i][0] == X[i + 1][0] or (i > 0 and X[i][0] == X[i - 1][0]):
		ans += X[i][1]
		S.add(X[i][0])
	else:
		Y.append(X[i])
for (a, b) in Y:
	T = False
	for s in S:
		if a & s == a:
			T = True
			break
	if T:
		ans += b
print(ans)


from sys import stdin, stdout
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
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 smp():
	return map(str, 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 remadd(x, y):
	return 1 if x % y else 0

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 = iinp()
arr = lmp()
barr = lmp()
inds = l2d(n, 60, 0)
for i in range(n):
	x = arr[i]
	j = 0
	while x:
		inds[i][j] = x % 2
		x //= 2
		j += 1

def cmp(a, b):
	for i in range(60):
		if inds[a][i] and (not inds[b][i]):
			return False
	return True
c = 0
cnt = dd(int)
for i in arr:
	cnt[i] += 1
s = set()
for i in range(n):
	if cnt[arr[i]] > 1:
		c += barr[i]
		s.add(i)
if c == 0:
	print(0)
	exit()
for i in range(n):
	if cnt[arr[i]] == 1:
		flg = False
		for j in s:
			if cmp(i, j):
				flg = True
				break
		if flg:
			s.add(i)
			c += barr[i]
print(c)


from collections import defaultdict
n = int(input().split()[0])
a = list(map(int, input().split()))
b = list(map(int, input().split()))
types = defaultdict(list)
for i in range(n):
	types[a[i]].append(b[i])
(res, selected) = (0, set())
for (k, v) in types.items():
	if len(v) > 1:
		res += sum(v)
		selected.add(k)
for (k, v) in types.items():
	if len(v) == 1:
		for j in selected:
			if k | j == j:
				res += v[0]
				break
print(res)


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 = int(input())
algo = list(map(int, input().split()))
skill = list(map(int, input().split()))
dict1 = {}
dict2 = {}
for s in range(n):
	nums = algo[s]
	if not nums in dict1:
		dict1[nums] = 1
		dict2[nums] = skill[s]
	else:
		dict1[nums] += 1
		dict2[nums] += skill[s]
maxsofar = 0
keys = []
for s in dict1.keys():
	keys.append(s)
for s in keys:
	if s in dict1:
		if dict1[s] >= 2:
			popkeys = []
			if s != 0:
				for j in dict1.keys():
					if s ^ j == max(s, j) - min(s, j) and j != s and (j != 0) and (j < s):
						dict2[s] += dict2[j]
						popkeys.append(j)
						dict1[s] += dict1[j]
			for j in range(len(popkeys)):
				dict1.pop(popkeys[j])
				dict2.pop(popkeys[j])
for s in dict1.keys():
	if dict1[s] >= 2:
		skills = dict2[s]
		if s != 0:
			for j in dict1.keys():
				if s != j and dict1[j] >= 2 and (j != 0):
					skills += dict2[j]
		if skills > maxsofar:
			maxsofar = skills
print(maxsofar)


from collections import defaultdict
from collections import Counter
import sys
sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
D_A = defaultdict(int)
for (a, b) in zip(A, B):
	D_A[a] += b
C_A = Counter(A)
leader_cand = set()
for (n, v) in C_A.most_common():
	if v >= 2:
		leader_cand.add(n)
ans = 0
for (key, val) in D_A.items():
	if key in leader_cand:
		ans += D_A[key]
	else:
		for lead in leader_cand:
			if key | lead == lead:
				ans += D_A[key]
				break
print(ans)


n = int(input())
lst1 = list(map(int, input().split()))[:n]
lst2 = list(map(int, input().split()))[:n]
dict = {}
for a in lst1:
	if a in dict:
		dict[a] += 1
	else:
		dict[a] = 1
ans = 0
grp = []
for k in dict:
	if dict[k] > 1:
		grp.append(k)
for i in range(n):
	for k in grp:
		if lst1[i] | k == k:
			ans += lst2[i]
			break
print(ans)


from collections import Counter

def main():
	n = int(input())
	A = tuple(map(int, input().split()))
	B = tuple(map(int, input().split()))
	C = Counter(A)
	if C.most_common()[0][1] == 1:
		return 0
	skill = set()
	for (key, cnt) in C.most_common():
		if cnt == 1:
			break
		skill.add(key)
	ans = 0
	for (a, b) in zip(A, B):
		for s in skill:
			if s | a == s:
				ans += b
				break
	return ans
print(main())


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
freq = {}
for i in a:
	freq[i] = [0, 0]
for i in range(len(a)):
	freq[a[i]][0] += 1
	freq[a[i]][1] += b[i]
ans = 0
gr = {}
for i in freq:
	if freq[i][0] > 1:
		gr[i] = freq[i]
		ans += freq[i][1]
for i in freq:
	if freq[i][0] == 1:
		flag = 0
		for k in gr:
			if k & i == i:
				flag = 1
		if flag == 1:
			ans += freq[i][1]
print(ans)


from collections import defaultdict
import sys
n = int(input())
a = [int(val) for val in input().split()]
b = [int(val) for val in input().split()]
groups = defaultdict(lambda : {'count': 0, 'skill': 0})
for (i, val) in enumerate(a):
	groups[val]['count'] += 1
	groups[val]['skill'] += b[i]
if len(groups) == n:
	print(0)
	return
group = []
output = 0
individuals = []
for (val, desc) in list(groups.items()):
	if desc['count'] == 1:
		individuals.append((val, desc['skill']))
	else:
		group.append(val)
		output += desc['skill']
for (ival, skill) in individuals:
	valid = False
	for gval in group:
		if ival | gval == gval:
			valid = True
	if valid:
		output += skill
print(output)


from sys import stdin
from collections import Counter
input = stdin.readline

def camp():
	n = int(input())
	lst1 = list(map(int, input().split()))
	lst2 = list(map(int, input().split()))
	arr = []
	for i in lst1:
		x = bin(i)[2:]
		arr.append('0' * (60 - len(x)) + x)
	cnt = Counter(arr)
	if max(cnt.values()) == 1:
		return 0
	lst = set()
	for (i, j) in cnt.items():
		if j >= 2:
			lst.add(i)
	s = 0
	for i in range(n):
		x = arr[i]
		if x in lst:
			s += lst2[i]
		else:
			for j in lst:
				flag = 1
				for k in range(60):
					if x[k] == '1' and j[k] != '1':
						flag = 0
						break
				if flag:
					s += lst2[i]
					break
	return s
print(camp())


n = int(input())
ta = list(map(int, input().split()))
a = []
tb = list(map(int, input().split()))
cnt = {}
for i in range(n):
	if ta[i] not in cnt:
		cnt[ta[i]] = 1
	else:
		cnt[ta[i]] += 1
s1 = []
for i in range(n):
	if cnt[ta[i]] > 1:
		s1.append(ta[i])

def bin(num):
	s = set()
	for j in range(61, -1, -1):
		bit = num >> j
		if bit > 0:
			if bit & 1:
				s.add(j)
	return s
ans = 0
for i in range(n):
	for j in s1:
		if j | ta[i] == j:
			ans += tb[i]
			break
print(ans)


import sys
input = sys.stdin.readline
from collections import Counter
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = Counter(A)
ans = 0
P = set(list(range(N)))
for (bit, count) in C.items():
	if count == 1:
		continue
	must = []
	for p in P:
		if bit | A[p] == bit:
			must.append(p)
			ans += B[p]
	for p in must:
		P.remove(p)
print(ans)


import os
import sys
from collections import Counter
from io import BytesIO, IOBase
import os
import sys
from io import BytesIO, IOBase

def main():
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	ma = 0
	z = Counter()
	x = Counter(a)
	an = 0
	vis = [0] * n
	for i in x:
		if x[i] > 1:
			for j in range(n):
				if a[j] != i and x[a[j]] == 1 and (a[j] | i == i) and (not vis[j]):
					an += b[j]
					vis[j] = 1
				if a[j] == i:
					an += b[j]
	print(an)
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 = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
d = {}
for i in range(len(a)):
	if a[i] in d:
		d[a[i]][0] += b[i]
		d[a[i]][1] += 1
	else:
		d[a[i]] = [b[i], 1]
s = 0
currset = set()
countmax = 0
to = 0
for i in d:
	if d[i][1] > 1:
		s += d[i][0]
		(num, temp) = (bin(i)[2:], bin(i)[2:].count('1'))
		currset.add(('0' * (60 - len(num)) + num, temp))
		countmax = max(countmax, temp)
		to = 1
for i in range(len(a)):
	a[i] = [a[i], b[i]]
for i in range(len(a)):
	(a[i], b[i]) = (a[i][0], a[i][1])
for i in range(len(a)):
	if d[a[i]][1] == 1:
		temp = bin(a[i])[2:]
		temp = '0' * (60 - len(temp)) + temp
		temp2 = temp.count('1')
		if temp2 <= countmax:
			for j in currset:
				if j[1] >= temp2:
					curr = 1
					for k in range(60):
						if j[0][k] == '0' and temp[k] == '1':
							curr = 0
							break
					if curr:
						s += b[i]
						break
		to += 1
print(s if to else 0)


import math
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')
import sys
n = int(input())
l = list(map(int, input().split()))
sw = list(map(int, input().split()))
if len(set(l)) == n:
	print(0)
	sys.exit()
d = set()
s = set()
for i in range(n):
	if l[i] in s:
		d.add(l[i])
	s.add(l[i])
bit = dict()
for j in d:
	r = bin(j)[2:]
	w = set()
	for i in range(len(r)):
		if r[i] == '1':
			w.add(len(r) - 1 - i)
	bit.update({j: w})
a = []
for i in range(n):
	r = bin(l[i])[2:]
	w = set()
	for i in range(len(r)):
		if r[i] == '1':
			w.add(len(r) - 1 - i)
	a.append(w)
ans = 0
s = set()
for j in bit:
	for i in range(n):
		if l[i] == j:
			ans += sw[i]
			continue
		if l[i] in s or l[i] in bit:
			continue
		if j | l[i] == j:
			ans += sw[i]
			s.add(l[i])
	s.add(j)
print(ans)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
ii = lambda : int(input())
kk = lambda : map(int, input().split())
ll = lambda : list(kk())
n = ii()
vals = zip(kk(), kk())
d = {}
for v in vals:
	if v[0] not in d:
		d[v[0]] = []
	d[v[0]].append(v[1])
d2 = {k: sum(d[k]) for k in d}
maxs = 0
if 0 not in d:
	(d[0], d2[0]) = ([0], 0)
ls = sorted(d.keys(), reverse=True)
ans = {l: 0 for l in ls}
valid = {l: 0 for l in ls}
for k in ls:
	if len(d[k]) > 1:
		valid[k] = 1
	for k2 in ls:
		if k2 < k:
			break
		if valid[k2] and k & k2 == k:
			valid[k] = 1
			ans[k] += d2[k2]
print(ans[0])


n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
vis = [False] * n
s = sorted(zip(a, b))
c = 1
L1 = []
L2 = []
ans = 0
h = s[0][1]
for i in range(1, len(s)):
	if s[i][0] != s[i - 1][0]:
		if c > 1:
			L1.append(s[i - 1][0])
			ans += h
		else:
			L2.append(s[i - 1])
		c = 1
		h = s[i][1]
	else:
		c += 1
		h += s[i][1]
if c > 1:
	L1.append(s[-1][0])
	ans += h
else:
	L2.append(s[-1])
for i in range(0, len(L2)):
	for j in range(0, len(L1)):
		if L2[i][0] | L1[j] == L1[j]:
			ans += L2[i][1]
			break
print(ans)


t = int(input())
algo = [int(i) for i in input().split()]
strength = [int(i) for i in input().split()]
dict1 = {}
dict2 = {}
binary = {}
max_strength = 0
for i in range(len(algo)):
	if algo[i] in dict1:
		binary[algo[i]] = bin(algo[i])[2:]
		dict1[algo[i]] += 1
		if dict1[algo[i]] == 2:
			max_strength += dict2[algo[i]] + strength[i]
		else:
			max_strength += strength[i]
	else:
		dict1[algo[i]] = 1
		dict2[algo[i]] = strength[i]
for i in range(t):
	ok = True
	if algo[i] not in binary:
		bunu = bin(algo[i])[2:]
		for j in binary:
			if len(bunu) <= len(binary[j]):
				sliced = binary[j][-len(bunu):]
				for ji in range(len(bunu)):
					if int(bunu[ji]) == 1 and int(sliced[ji]) != 1:
						ok = False
						break
				else:
					max_strength += strength[i]
					break
print(max_strength)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = []
for i in range(n):
	c.append((a[i], b[i]))
c.sort(reverse=True)
ins = []
cnt = 1
now = c[0][0]
tot = c[0][1]
i = 1
ans = 0
while 1:
	while i < n and c[i][0] == now:
		tot += c[i][1]
		i += 1
		cnt += 1
	if cnt >= 2:
		ins.append(now)
		ans += tot
	if cnt == 1:
		for j in ins:
			if now & j == now:
				ins.append(now)
				ans += tot
				break
	if i >= n:
		break
	now = c[i][0]
	cnt = 1
	tot = c[i][1]
	i += 1
print(ans)


n = int(input())
info = {}
state = []
str = input()
list1 = str.split(' ')
for i in range(n):
	aa = int(list1[i])
	state.append(aa)
	if info.get(aa) == None:
		info[aa] = {1: 0, 2: False}
	else:
		info[aa] = {1: 0, 2: True}
str = input()
list1 = []
list1 = str.split(' ')
for i in range(n):
	bb = int(list1[i])
	info[state[i]][1] = bb + info[state[i]][1]
ans = 0
inside = []
outside = []
for i in info:
	if info[i][2] == True:
		ans = ans + info[i][1]
		inside.append(i)
	else:
		outside.append(i)
inside.sort(reverse=True)
outside.sort()
nn = len(inside)
iiii = 0
ii = 0
has = {}
for i in inside:
	has[i] = 1
	for j in outside:
		if i & j == j:
			has[j] = 1
ans = 0
for i in has:
	ans = ans + info[i][1]
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 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
from math import gcd
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
n = int(ri())
a = Ri()
b = Ri()
ans = 0
dic = {}
for i in a:
	dic[i] = dic.get(i, 0) + 1
for i in range(n):
	if dic[a[i]] > 1:
		ans += b[i]
	else:
		for j in dic:
			if dic[j] > 1 and j & a[i] == a[i]:
				ans += b[i]
				break
print(ans)


n = int(input())
b = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
rev = {}
dic = {}
for i in range(n):
	bb = b[i]
	if bb in dic:
		dic[bb].append(i)
	else:
		dic[bb] = [i]
neg1 = (1 << 60) - 1
ans = 0
mask = 0
dels = []
for bb in dic:
	inds = dic[bb]
	if len(inds) > 1:
		for ind in inds:
			ans += a[ind]
		mask |= bb
		dels.append(bb)
if ans == 0:
	print(0)
	exit()
dic2 = {}
l2 = []
heads = []
for bb in dels:
	dic2[bb] = bin(bb).count('1')
	l2.append(bb)
	del dic[bb]
l2.sort(key=lambda q: dic2[q], reverse=True)
for l in l2:
	subs = False
	for h in heads:
		if l | ~h & neg1 == neg1:
			subs = True
			break
	if not subs:
		heads.append(l)
for bb in dic:
	subs = False
	for h in heads:
		if h | ~bb & neg1 == neg1:
			subs = True
			break
	if subs:
		ans += a[dic[bb][0]]
print(ans)


ii = lambda : int(input())
kk = lambda : map(int, input().split())
ll = lambda : list(kk())
n = ii()
vals = zip(kk(), kk())
d = {}
for v in vals:
	if v[0] not in d:
		d[v[0]] = []
	d[v[0]].append(v[1])
d2 = {k: sum(d[k]) for k in d}
maxs = 0
if 0 not in d:
	(d[0], d2[0]) = ([0], 0)
ls = sorted(d.keys(), reverse=True)
ans = {l: 0 for l in ls}
valid = {l: 0 for l in ls}
for k in ls:
	if len(d[k]) > 1:
		valid[k] = 1
	for k2 in ls:
		if k2 < k:
			break
		if valid[k2] and k & k2 == k:
			valid[k] = 1
			ans[k] += d2[k2]
print(ans[0])


def bitcode(lis):
	bc = []
	for n in lis:
		if lis[n] > 1:
			bc.append(n)
	return bc
n = int(input())
lis = {}
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for bc in a:
	try:
		lis[bc] += 1
	except:
		lis[bc] = 1
bcs = bitcode(lis)
if len(bcs) == 0:
	print(0)
else:
	bsum = 0
	for i in range(n):
		if lis[a[i]] > 1:
			bsum += b[i]
			continue
		for bc in bcs:
			if a[i] & ~bc == 0:
				bsum += b[i]
				break
	print(bsum)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
s = list(zip(a, b))
s.sort(reverse=True)
i = 0
ans = 0
vz = []
while i < n:
	j = i + 1
	while j < n and s[j][0] == s[i][0]:
		j += 1
	if j - i > 1:
		vz.extend(s[i:j])
	else:
		for e in vz:
			if e[0] | s[i][0] == e[0]:
				vz.append(s[i])
				break
	i = j
print(sum(map(lambda x: x[1], vz)))


import math

def count_digits(x):
	result = 0
	while x > 0:
		x &= x - 1
		result += 1
	return result

def main():
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	sk = []
	occ = dict()
	inv = dict()
	for i in range(61):
		sk.append([])
	for i in range(n):
		if a[i] in occ:
			occ[a[i]] += 1
			inv[a[i]].append(b[i])
		else:
			sk[count_digits(a[i])].append(a[i])
			occ[a[i]] = 1
			inv[a[i]] = [b[i]]
	result = 0
	students = []
	for i in reversed(range(61)):
		for skill in sk[i]:
			if occ[skill] > 1:
				result += sum(inv[skill])
				students.append(skill)
			else:
				valid = False
				for s in students:
					if skill | s == s:
						valid = True
						break
				if valid:
					result += sum(inv[skill])
					students.append(skill)
	print(result)
main()


import sys
input = sys.stdin.readline
from collections import defaultdict
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = defaultdict(int)
for i in range(n):
	c[a[i]] += 1
s = 0
for i in range(n):
	for j in c:
		if c[j] > 1:
			if j | a[i] == j:
				s += b[i]
				break
print(s)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
d = {}
for i in range(n):
	if a[i] not in d:
		d[a[i]] = []
	d[a[i]].append(b[i])
res = 0
v = []
for i in d.keys():
	if len(d[i]) > 1:
		v.append(i)
		res += sum(d[i])
for i in d.keys():
	if len(d[i]) == 1:
		for j in v:
			if i & j == i:
				v.append(i)
				res += d[i][0]
				break
print(res)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
from collections import defaultdict
hash = defaultdict(int)
for (i, j) in enumerate(a):
	hash[j] += 1
res = 0
for i in range(n):
	for k in hash:
		if hash[k] > 1:
			if a[i] | k == k:
				res += b[i]
				break
print(res)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ad = set()
duplicates = set()
for i in a:
	if i in ad:
		duplicates.add(i)
	ad.add(i)
total = 0
for (i, ai) in enumerate(a):
	if ai in duplicates:
		total += b[i]
		continue
	for d in duplicates:
		if ai & d == ai:
			total += b[i]
			break
print(total)


import sys
input = sys.stdin.readline

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 main():
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	d = {}
	f = {}
	for i in range(n):
		if a[i] not in d:
			d[a[i]] = b[i]
			f[a[i]] = 1
		else:
			d[a[i]] += b[i]
			f[a[i]] += 1
	ans = 0
	used = [0] * n
	for i in list(f.keys()):
		if f[i] > 1:
			for j in range(n):
				if i | a[j] == i and (not used[j]):
					used[j] = 1
	for i in range(n):
		if used[i]:
			ans += b[i]
	print(ans)
	return

def __starting_point():
	main()
__starting_point()


from collections import Counter

def main():
	n = int(input())
	a = readIntArr()
	b = readIntArr()
	cnts = Counter(a)
	visited = [False] * n
	ans = 0
	for i in range(n):
		if cnts[a[i]] >= 2 and (not visited[i]):
			ans += b[i]
			visited[i] = True
			stack = [a[i]]
			while stack:
				mask = stack.pop()
				for j in range(n):
					if mask | a[j] == mask and (not visited[j]):
						visited[j] = True
						ans += b[j]
						stack.append(a[j])
	print(ans)
	return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

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

def makeArr(defaultValFactory, dimensionArr):
	dv = defaultValFactory
	da = dimensionArr
	if len(da) == 1:
		return [dv() for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(i, j):
	print('? {} {}'.format(i, j))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(' '.join([str(x) for x in ans])))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
for _abc in range(1):
	main()


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
vis = [0 for i in range(len(a))]
c = []
d = {}
for i in range(len(a)):
	if a[i] in d:
		d[a[i]].append(i)
	else:
		d[a[i]] = [i]
ans = 0
for i in d.keys():
	if len(d[i]) >= 2:
		for j in d[i]:
			ans += b[j]
			vis[j] = 1
			c.append(a[j])
c = set(c)
for i in range(len(a)):
	if vis[i] == 0:
		for j in c:
			if j > a[i] and j & a[i] == a[i]:
				c.add(a[i])
				ans += b[i]
				break
print(ans)