Arthur has bought a beautiful big table into his new flat. When he came home, Arthur noticed that the new table is unstable.

In total the table Arthur bought has n legs, the length of the i-th leg is l_{i}.

Arthur decided to make the table stable and remove some legs. For each of them Arthur determined number d_{i} — the amount of energy that he spends to remove the i-th leg.

A table with k legs is assumed to be stable if there are more than half legs of the maximum length. For example, to make a table with 5 legs stable, you need to make sure it has at least three (out of these five) legs of the maximum length. Also, a table with one leg is always stable and a table with two legs is stable if and only if they have the same lengths.

Your task is to help Arthur and count the minimum number of energy units Arthur should spend on making the table stable.


-----Input-----

The first line of the input contains integer n (1 ≤ n ≤ 10^5) — the initial number of legs in the table Arthur bought.

The second line of the input contains a sequence of n integers l_{i} (1 ≤ l_{i} ≤ 10^5), where l_{i} is equal to the length of the i-th leg of the table.

The third line of the input contains a sequence of n integers d_{i} (1 ≤ d_{i} ≤ 200), where d_{i} is the number of energy units that Arthur spends on removing the i-th leg off the table.


-----Output-----

Print a single integer — the minimum number of energy units that Arthur needs to spend in order to make the table stable.


-----Examples-----
Input
2
1 5
3 2

Output
2

Input
3
2 4 4
1 1 1

Output
0

Input
6
2 2 1 1 3 3
4 3 5 5 2 1

Output
8

Difficulty: HARD
Tags: Sorting

Complete search

Greedy algorithms

Dynamic programming

Mathematics

Data structures
Skill types: Sorting

Greedy algorithms

Complete search

Dynamic programming

Data structures

Starter code:

Solutions:
MAX_D = 201
n = int(input())
l = list(map(int, input().split()))
d = list(map(int, input().split()))
legs = sorted(list(zip(l, d)))
d_suffix = [legs[0][1]]
for i in range(1, n):
	d_suffix.append(d_suffix[-1] + legs[i][1])
ans = d_suffix[-1]
cnt = {}
left = 0
right = 0
while left < n:
	while right < n and legs[left][0] == legs[right][0]:
		right += 1
	to_remove = left - (right - left - 1)
	curr_d = d_suffix[-1] - d_suffix[right - 1]
	for i in range(1, MAX_D):
		if to_remove <= 0:
			break
		used = min(to_remove, cnt.get(i, 0))
		to_remove -= used
		curr_d += used * i
	ans = min(ans, curr_d)
	while left < right:
		cnt[legs[left][1]] = cnt.get(legs[left][1], 0) + 1
		left += 1
print(ans)


def buscaEnergia(perna, qtd):
	total = 0
	if qtd == 0:
		return total
	for i in range(len(d) - 1, -1, -1):
		for v in d[i]:
			if v < perna:
				qtd -= 1
				total += i
			else:
				break
			if qtd == 0:
				break
		if qtd == 0:
			break
	return total
n = int(input())
tamanhoPerna = [int(i) for i in input().split()]
energiaPerna = [int(i) for i in input().split()]
d = [[] for i in range(201)]
cntPerna = [0] * 100001
sumPerna = [0] * 100001
corteTotal = 0
maxTam = 0
for i in range(len(tamanhoPerna)):
	d[energiaPerna[i]].append(tamanhoPerna[i])
	sumPerna[tamanhoPerna[i]] += energiaPerna[i]
	cntPerna[tamanhoPerna[i]] += 1
	corteTotal += energiaPerna[i]
	maxTam = max(tamanhoPerna[i], maxTam)
for i in range(len(d)):
	d[i].sort()
currentMin = float('inf')
for perna in tamanhoPerna:
	somaMesa = sumPerna[perna]
	somaMesa += buscaEnergia(perna, cntPerna[perna] - 1)
	currentMin = min(currentMin, corteTotal - somaMesa)
print(currentMin)


f = lambda : map(int, input().split())
(k, n) = (1, f())
s = sorted(zip(f(), f()), key=lambda q: q[0])
t = [0] * 201
for (l, d) in s:
	t[d] += 1
j = [i for i in range(201) if t[i]]
j.reverse()
S = sum((i * t[i] for i in j))
(L, D) = s.pop()
t[D] -= 1
s.reverse()
s.append((0, 0))
m = 0
for (l, d) in s:
	if l < L:
		L = l
		for i in j:
			if t[i] > k - 2:
				D += i * (k - 1)
				break
			D += i * t[i]
			k -= t[i]
		m = max(m, D)
		k = D = 0
	k += 1
	D += d
	t[d] -= 1
	if not t[d]:
		j.remove(d)
print(S - m)


n = int(input())
legs = list(zip(list(map(int, input().split())), list(map(int, input().split()))))
legs.sort(key=lambda x: x[1], reverse=True)
cnt = {}
s = 0
for i in range(n):
	s += legs[i][1]
	if legs[i][0] not in cnt:
		cnt[legs[i][0]] = [1, legs[i][1]]
	else:
		cnt[legs[i][0]][0] += 1
		cnt[legs[i][0]][1] += legs[i][1]
temp = sorted(cnt.items())
mn = 9999999999999
f = 0
while temp:
	(l, t) = temp.pop()
	(c, e) = t
	s -= e
	val = s
	i = 0
	count = 0
	while count < c - 1:
		if legs[i][0] < l:
			count += 1
			val -= legs[i][1]
		i += 1
		if i == n:
			break
	if val + f < mn:
		mn = val + f
	f += e
print(mn)


rr = lambda : list(map(int, input().split()))
(_, d, res, he) = (input(), {}, 0, list(zip(rr(), rr())))
for (h, e) in he:
	(f, x) = d.get(h, (-1, 0))
	d[h] = (f + 1, x + e)
he.sort(key=lambda x: x[1], reverse=True)
for (h, (f, x)) in list(d.items()):
	if not f:
		res = max(x, res)
		continue
	for (h1, e) in he:
		if h1 < h:
			x += e
			f -= 1
			if not f:
				break
	res = max(x, res)
print(sum((e for (h, e) in he)) - res)


n = int(input())
INF = -1
arr = [0] * n
d = [0] * 201
l = list(map(int, input().split()))
e = list(map(int, input().split()))
s = 0
for i in range(n):
	arr[i] = (l[i], e[i])
	s += e[i]
	d[e[i]] += 1
l = []
e = []
ans = [INF] * 3
ans[2] = 10 ** 10
p = arr[-1][0]
k = [0, 0]
arr.sort()
arr = [(-1, -1)] + arr
e = 0
c = 0
for i in range(n, -1, -1):
	if arr[i][0] == p:
		c += 1
		e += arr[i][1]
		d[arr[i][1]] -= 1
	else:
		if c == 1:
			ans[0] = max(ans[0], e)
		elif c == 2:
			ans[1] = max(ans[1], arr[i + 1][1] + arr[i + 2][1])
		if c >= 2:
			mx = c + c - 1
			eng = k[1]
			if k[0] >= n - mx:
				ans[2] = min(ans[2], eng)
			else:
				g = n - mx - k[0]
				j = 1
				while j < 201 and g > 0:
					if d[j] > 0:
						if g > d[j]:
							eng += d[j] * j
							g -= d[j]
						else:
							eng += g * j
							g = 0
					j += 1
				if g == 0:
					ans[2] = min(ans[2], eng)
		k[0] += c
		k[1] += e
		c = 1
		e = arr[i][1]
		d[arr[i][1]] -= 1
		p = arr[i][0]
mn = 10 ** 10
for i in range(2):
	ans[i] = s - ans[i]
for i in range(3):
	if ans[i] != -1 and mn > ans[i]:
		mn = ans[i]
if mn != 10 ** 10:
	print(mn)
else:
	print(0)


f = lambda : list(map(int, input().split()))
(n, p, m, s) = (input(), {}, 0, sorted(zip(f(), f()), key=lambda q: -q[1]))
for (L, d) in s:
	(k, D) = p.get(L, (-1, 0))
	p[L] = (k + 1, D + d)
for (L, (k, D)) in list(p.items()):
	if k:
		for (l, d) in s:
			if l < L:
				D += d
				k -= 1
				if k == 0:
					break
	m = max(D, m)
print(sum((d for (l, d) in s)) - m)


from sys import stdin, stdout

def main():
	n = int(stdin.readline())
	leg = [int(_) for _ in stdin.readline().split()]
	d = [int(_) for _ in stdin.readline().split()]
	pairedLD = []
	for (x, y) in zip(leg, d):
		pairedLD.append((x, y))
	pairedLD = sorted(pairedLD)
	legSet = set()
	suffixSum = dict()
	legFreq = dict()
	for (length, energy) in zip(leg, d):
		legSet.add(length)
		if length in suffixSum:
			suffixSum[length] += energy
			legFreq[length] += 1
		else:
			suffixSum[length] = energy
			legFreq[length] = 1
	legList = [x for x in legSet]
	legList = sorted(legList, reverse=True)
	total = 0
	for length in legList:
		suffixSum[length] += total
		total = suffixSum[length]
	ans = int(20000000.0)
	toRemove = 0
	available = 0
	removable = [0] * 201
	legList = sorted(legList)
	listLen = len(legList)
	idx = 0
	for i in range(listLen):
		curr = 0
		if i + 1 < listLen:
			curr += suffixSum[legList[i + 1]]
		toRemove = available - (legFreq[legList[i]] - 1)
		if toRemove < 0:
			toRemove = 0
		for j in range(1, 201):
			if removable[j] != 0 and removable[j] <= toRemove:
				curr += removable[j] * j
				toRemove -= removable[j]
			elif removable[j] > toRemove:
				curr += toRemove * j
				toRemove = 0
			if toRemove == 0:
				break
		available += legFreq[legList[i]]
		for j in range(legFreq[legList[i]]):
			removable[pairedLD[idx][1]] += 1
			idx += 1
		ans = min(ans, curr)
	print(ans)

def __starting_point():
	main()
__starting_point()


def main():
	(_, dd, res) = (input(), {}, 0)
	he = list(zip(list(map(int, input().split())), list(map(int, input().split()))))
	for (h, e) in he:
		(le, x) = dd.get(h, (-1, 0))
		dd[h] = (le + 1, x + e)
	he.sort(key=lambda _: _[1], reverse=True)
	for (h, (le, x)) in list(dd.items()):
		if le:
			for (h1, e) in he:
				if h1 < h:
					x += e
					le -= 1
					if not le:
						break
		if res < x:
			res = x
	print(sum((e for (h, e) in he)) - res)

def __starting_point():
	main()
__starting_point()


import unittest
import sys
import re
import random
import bisect

class Table:
	LIM = 201

	def __init__(self, args):
		self.legs = args[0]
		self.energy = args[1]
		self.n = len(self.legs)
		self.srt = sorted(((l, e) for (l, e) in zip(self.legs, self.energy)))
		self.legs = []
		self.energy = []
		for n in self.srt:
			self.legs.append(n[0])
			self.energy.append(n[1])
		self.itot = 0
		self.ieltot = [0 for i in range(self.LIM)]
		self.ielprev = [0 for i in range(self.LIM)]
		self.ielprev_eng = 0
		self.ires_eng = sys.maxsize

	def get_new_layer_info(self, legs, energy):
		ll = len(legs)
		for (i, l) in enumerate(legs):
			self.ilen = l
			e = energy[i]
			if i == 0:
				self.itop_eng = sum(energy)
			if i == 0 or self.ilen != prev:
				self.irep = 0
				self.ielsum_eng = 0
				self.ielprev = list(self.ieltot)
			self.irep += 1
			self.itop_eng -= e
			self.ielprev_eng += e
			self.ielsum_eng += e
			self.ieltot[e] += 1
			if i == ll - 1 or legs[i + 1] != self.ilen:
				self.irem = self.irep - 1
				self.irem_eng = self.ielprev_eng - self.ielsum_eng
				if self.irem != 0:
					sumh = self.energyl_sum_high(self.ielprev, self.irem)
					self.irem_eng -= sumh
				summ = self.itop_eng + self.irem_eng
				self.ires_eng = min(self.ires_eng, summ)
				yield
			prev = self.ilen

	def energyl_sum_high(self, l, n):
		result = 0
		for i in range(len(l) - 1, -1, -1):
			e = l[i]
			if e == 0:
				continue
			if n <= 0:
				break
			result += i * (n if e > n else e)
			n -= e
		return result

	def calculate(self):
		iter = self.get_new_layer_info(self.legs, self.energy)
		for g in iter:
			pass
		result = self.ires_eng
		return str(result)

def get_inputs(test_inputs=None):
	it = iter(test_inputs.split('\n')) if test_inputs else None

	def uinput():
		if it:
			return next(it)
		else:
			return input()
	num = int(uinput())
	str1 = [int(s) for s in uinput().split()]
	str2 = [int(s) for s in uinput().split()]
	inputs = []
	inputs.append(str1)
	inputs.append(str2)
	return inputs

def calculate(test_inputs=None):
	return Table(get_inputs(test_inputs)).calculate()

class unitTests(unittest.TestCase):

	def test_sample_tests(self):
		imax = 100000
		test = '0\n'
		for i in range(imax):
			test += str(i) + ' '
		test += '\n'
		for i in range(imax):
			test += str(random.randint(1, 200)) + ' '
		calculate(test)
		test = '2\n1 5\n3 2'
		self.assertEqual(calculate(test), '2')
		self.assertEqual(get_inputs(test), [[1, 5], [3, 2]])
		test = '3\n2 4 4\n1 1 1'
		self.assertEqual(calculate(test), '0')
		test = '6\n2 2 1 1 3 3\n4 3 5 5 2 1'
		self.assertEqual(calculate(test), '8')
		test = '10\n20 1 15 17 11 2 15 3 16 3\n' + '129 114 183 94 169 16 18 104 49 146'
		self.assertEqual(calculate(test), '652')

	def test_Table_class__basic_functions(self):
		d = Table([[2, 2, 1, 1, 3, 3], [2, 2, 3, 3, 1, 1]])
		self.assertEqual(d.legs[0], 1)
		self.assertEqual(d.energy[0], 3)
		iter = d.get_new_layer_info([1, 1, 2, 2, 4, 5], [2, 2, 3, 3, 1, 1])
		next(iter)
		self.assertEqual(d.itop_eng, 8)
		self.assertEqual(d.ilen, 1)
		self.assertEqual(d.irep, 2)
		self.assertEqual(d.irem, 1)
		self.assertEqual(d.irem_eng, 0)
		self.assertEqual(d.ires_eng, 8)
		next(iter)
		self.assertEqual(d.ilen, 2)
		self.assertEqual(d.irep, 2)
		self.assertEqual(d.irem, 1)
		self.assertEqual(d.irem_eng, 2)
		self.assertEqual(d.ires_eng, 4)
		d = Table([[], []])
		iter = d.get_new_layer_info([1, 1, 2, 2, 3, 3], [5, 5, 4, 3, 2, 1])
		next(iter)
		self.assertEqual(d.ilen, 1)
		self.assertEqual(d.irep, 2)
		self.assertEqual(d.irem, 1)
		self.assertEqual(d.irem_eng, 0)
		self.assertEqual(d.ires_eng, 10)
		next(iter)
		self.assertEqual(d.ilen, 2)
		self.assertEqual(d.irep, 2)
		self.assertEqual(d.irem, 1)
		self.assertEqual(d.irem_eng, 5)
		self.assertEqual(d.ires_eng, 8)
		next(iter)
		self.assertEqual(d.ilen, 3)
		self.assertEqual(d.irep, 2)
		self.assertEqual(d.irem, 1)
		self.assertEqual(d.irem_eng, 12)
		self.assertEqual(d.ires_eng, 8)
sys.setrecursionlimit(100000)
if sys.argv[-1] == '-ut':
	unittest.main(argv=[' '])
print(calculate())


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
arr = list(zip(a, b))
(d, res) = ({}, 0)
for (i, j) in arr:
	(f, x) = d.get(i, (-1, 0))
	d[i] = (f + 1, x + j)
arr.sort(key=lambda x: x[1], reverse=True)
for (it, (f, x)) in d.items():
	if not f:
		res = max(x, res)
		continue
	for (i, j) in arr:
		if i < it:
			x += j
			f -= 1
			if not f:
				break
	res = max(x, res)
print(sum((j for (i, j) in arr)) - res)


n = int(input())
lengths = list(map(int, input().split()))
costs = list(map(int, input().split()))
sum = 0
length_to_sum = {}
length_to_count = {}
cost_to_lengths = {}
for i in range(n):
	(length, cost) = (lengths[i], costs[i])
	sum += cost
	length_to_sum[length] = length_to_sum.setdefault(length, 0) + cost
	length_to_count[length] = length_to_count.setdefault(length, 0) + 1
	cost_to_lengths.setdefault(cost, []).append(length)
length_set = set(lengths)
for lengths in cost_to_lengths.values():
	lengths.sort()
unique_costs = list(reversed(sorted(cost_to_lengths.keys())))
best = -1
for length in length_set:
	total = sum - length_to_sum[length]
	seek = length_to_count[length] - 1
	if seek != 0:
		for cost in unique_costs:
			for x in cost_to_lengths[cost]:
				if x >= length:
					break
				total -= cost
				seek -= 1
				if seek == 0:
					break
			if seek == 0:
				break
	if best == -1 or total < best:
		best = total
print(best)


from sys import stdin, stdout, setrecursionlimit
input = stdin.readline
inf = float('inf')
from functools import cmp_to_key
from collections import defaultdict as dd
from collections import Counter, deque
from heapq import *
import math
from math import floor, ceil, sqrt

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

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

def getis():
	return map(str, input().strip().split())

def getls():
	return list(map(str, input().strip().split()))

def gets():
	return input().strip()

def geta():
	return int(input())

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

def solve():
	n = geta()
	a = getl()
	maxi = max(a) + 1
	d = getl()
	count = Counter(d)
	have = [{} for _ in range(maxi)]
	for i in range(n):
		if d[i] in have[a[i]]:
			have[a[i]][d[i]] += 1
		else:
			have[a[i]][d[i]] = 1
	ans = inf
	a = Counter(a)
	d = sorted(set(d))
	cost = 0
	for i in range(maxi - 1, 0, -1):
		if not have[i]:
			continue
		rem = max(0, n - (2 * a[i] - 1))
		temp = cost
		for j in have[i]:
			count[j] -= have[i][j]
			cost += j * have[i][j]
		for j in d:
			if not rem:
				break
			now = count[j]
			temp += min(rem, now) * j
			rem -= min(rem, now)
		ans = min(ans, temp)
		n -= a[i]
	print(ans)
solve()


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

def prod(a, mod=10 ** 9 + 7):
	ans = 1
	for each in a:
		ans = ans * each % mod
	return ans

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

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
	n = int(input())
	l = list(map(int, input().split()))
	d = list(map(int, input().split()))
	di = {}
	d2 = {}
	for i in range(n):
		if l[i] not in di:
			di[l[i]] = 0
			d2[l[i]] = []
		di[l[i]] += d[i]
		d2[l[i]] += [d[i]]
	sa = sorted(list(set(l)))
	suf = [0]
	sufrem = [0]
	for i in range(len(sa) - 1, -1, -1):
		suf += [suf[-1] + di[sa[i]]]
		sufrem += [sufrem[-1] + len(d2[sa[i]])]
	ans = 10 ** 18
	count = [0] * (10 ** 5 + 69)
	oof = [0] * 500
	for i in l:
		count[i] += 1
	bi = len(sa) - 1
	for each in sa:
		cnt = count[each]
		removable = max(0, n - sufrem[bi] - 2 * cnt + 1)
		total = suf[bi]
		bi -= 1
		for i in range(500):
			mi = min(removable, oof[i])
			removable -= mi
			total += i * mi
			if not removable:
				break
		ans = min(ans, total)
		for x in d2[each]:
			oof[x] += 1
	print(ans)


n = int(input())
leng = list(map(int, input().split()))
energy = list(map(int, input().split()))
sum = 0
lenSum = {}
lenCount = {}
custos = {}
for i in range(n):
	(length, custo) = (leng[i], energy[i])
	sum += custo
	lenSum[length] = lenSum.setdefault(length, 0) + custo
	lenCount[length] = lenCount.setdefault(length, 0) + 1
	custos.setdefault(custo, []).append(length)
conjuntoLen = set(leng)
for leng in custos.values():
	leng.sort()
listaEnergia = list(reversed(sorted(custos.keys())))
ans = -1
for length in conjuntoLen:
	total = sum - lenSum[length]
	find = lenCount[length] - 1
	if find != 0:
		for custo in listaEnergia:
			for x in custos[custo]:
				if x >= length:
					break
				total -= custo
				find -= 1
				if find == 0:
					break
			if find == 0:
				break
	if ans == -1 or total < ans:
		ans = total
print(ans)


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
import time
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
			self.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 collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
start_time = time.time()

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())

def getMat(n):
	return [getInts() for _ in range(n)]
MOD = 998244353

def solve():
	N = getInt()
	L = getInts()
	D = getInts()
	A = [(l, d) for (l, d) in zip(L, D)]
	A.sort()
	suffs = [0]
	curr = 0
	for i in range(N - 1, -1, -1):
		curr += A[i][1]
		suffs.append(curr)
	suffs.reverse()
	count = [0] * (10 ** 5 + 1)
	for (l, d) in A:
		count[l] += 1
	best = 10 ** 18
	cur_seen = 0
	j = 0
	k = 0
	diff_count = [0] * 201
	for i in range(1, 10 ** 5 + 1):
		if not count[i]:
			continue
		while k < N and A[k][0] == i:
			k += 1
		tmp = suffs[k]
		rem = k - count[i]
		diff = 0
		while count[i] <= rem:
			x = min(rem - count[i] + 1, diff_count[diff])
			rem -= x
			tmp += x * diff
			diff += 1
		best = min(tmp, best)
		for ii in range(j, k):
			diff_count[A[ii][1]] += 1
			cur_seen += 1
		j = k
		if j == N:
			break
	return best
print(solve())


from collections import defaultdict

def main():
	n = int(input())
	hh = list(map(int, input().split()))
	ee = list(map(int, input().split()))
	dd = defaultdict(set)
	for (i, h) in enumerate(hh):
		dd[h].add(i)
	idx = sorted(list(range(n)), key=ee.__getitem__, reverse=True)
	res = 0
	for (h, s) in list(dd.items()):
		x = sum((ee[i] for i in s))
		le = len(s) - 1
		if le:
			for i in idx:
				if hh[i] < h and i not in s:
					x += ee[i]
					le -= 1
					if not le:
						break
		if res < x:
			res = x
	print(sum(ee) - res)

def __starting_point():
	main()
__starting_point()


def read_data():
	n = int(input())
	Ls = list(map(int, input().split()))
	Ds = list(map(int, input().split()))
	return (n, Ls, Ds)

def solve(n, Ls, Ds):
	freqD = [0] * 201
	for d in Ds:
		freqD[d] += 1
	LDs = list(zip(Ls, Ds))
	LDs.sort(reverse=True)
	prevL = 0
	ni = 0
	record = float('inf')
	cost_long = 0
	cost_me = 0
	for (L, D) in LDs:
		if prevL != L:
			n -= ni
			record = min(record, cost_long + calc_cost(ni, n, freqD))
			prevL = L
			ni = 0
			cost_long += cost_me
			if cost_long >= record:
				return record
			cost_me = 0
		freqD[D] -= 1
		cost_me += D
		ni += 1
	record = min(record, cost_long)
	return record

def calc_cost(ni, n, freqD):
	if n < ni:
		return 0
	cost = 0
	for (d, f) in enumerate(freqD):
		if n - f >= ni:
			cost += f * d
			n -= f
		else:
			cost += (n - ni + 1) * d
			return cost
	return float('inf')
(n, Ls, Ds) = read_data()
print(solve(n, Ls, Ds))


def increment(d, key, energy):
	if key in d.keys():
		d[key][0] += 1
		d[key][1] += energy
	else:
		d[key] = [1, energy]
legs = int(input())
lengths = list(map(int, input().split()))
energies = list(map(int, input().split()))
pairsEL = []
for x in range(legs):
	pairsEL.append([energies[x], lengths[x]])
pairsEL.sort()
pairsEL.reverse()
lengthMap = {}
for x in range(legs):
	increment(lengthMap, lengths[x], energies[x])
totalEnergy = sum(energies)
maxEnergy = 0
for key in reversed(sorted(lengthMap.keys())):
	currEnergy = lengthMap[key][1]
	legsToAdd = lengthMap[key][0] - 1
	for pair in pairsEL:
		if pair[1] < key:
			if legsToAdd > 0:
				currEnergy += pair[0]
				legsToAdd -= 1
			else:
				break
	maxEnergy = max(maxEnergy, currEnergy)
print(totalEnergy - maxEnergy)