VK news recommendation system daily selects interesting publications of one of $n$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $i$ batch algorithm selects $a_i$ publications.

The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $i$-th category within $t_i$ seconds. 

What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.


-----Input-----

The first line of input consists of single integer $n$ — the number of news categories ($1 \le n \le 200\,000$).

The second line of input consists of $n$ integers $a_i$ — the number of publications of $i$-th category selected by the batch algorithm ($1 \le a_i \le 10^9$).

The third line of input consists of $n$ integers $t_i$ — time it takes for targeted algorithm to find one new publication of category $i$ ($1 \le t_i \le 10^5)$.


-----Output-----

Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.


-----Examples-----
Input
5
3 7 9 7 8
5 2 5 7 5

Output
6

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

Output
0



-----Note-----

In the first example, it is possible to find three publications of the second type, which will take 6 seconds.

In the second example, all news categories contain a different number of publications.

Difficulty: MEDIUM_HARD
Tags: Sorting

Data structures

Greedy algorithms
Skill types: Sorting

Data structures

Greedy algorithms

Starter code:

Solutions:
from sys import stdin
from collections import deque
mod = 10 ** 9 + 7
import sys
import random
from queue import PriorityQueue
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt, factorial, gcd, log2, inf, ceil
import heapq
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
from itertools import permutations
from math import factorial as f

def ncr(x, y):
	return f(x) // (f(y) * f(x - y))
from collections import defaultdict
from heapq import heappop, heappush, heapify
n = int(input())
a = list(map(int, input().split()))
t = list(map(int, input().split()))
d = defaultdict(list)
for i in range(n):
	d[a[i]].append(t[i])
heap2 = list(set(a))
heapify(heap2)
ans = 0
used = set()
heap = []
s = 0
while heap2:
	cur = heappop(heap2)
	if cur in used:
		continue
	used.add(cur)
	for ti in d[cur]:
		heappush(heap, -ti)
		s += ti
	ti = -heappop(heap)
	s -= ti
	ans += s
	if heap:
		heappush(heap2, cur + 1)
print(ans)


import heapq
n = int(input())
a = list(map(int, input().split()))
t = list(map(int, input().split()))
d = {}
for i in range(len(a)):
	if a[i] not in d:
		d[a[i]] = []
	d[a[i]].append(t[i])
k = list(d.keys())
heapq.heapify(k)
cost = 0
mxh = []
sum_ = 0
while k:
	key = heapq.heappop(k)
	for i in d[key]:
		sum_ += i
		heapq.heappush(mxh, -i)
	if not mxh:
		continue
	sum_ += heapq.heappop(mxh)
	cost += sum_
	if not mxh:
		continue
	if key + 1 not in d:
		heapq.heappush(k, key + 1)
		d[key + 1] = []
	del d[key]
print(cost)


from sys import stdin
from heapq import *

def fast3():
	import os, sys, atexit
	from io import BytesIO
	sys.stdout = BytesIO()
	_write = sys.stdout.write
	sys.stdout.write = lambda s: _write(s.encode())
	atexit.register(lambda : os.write(1, sys.stdout.getvalue()))
	return BytesIO(os.read(0, os.fstat(0).st_size)).readline
input = fast3()
rints = lambda : [int(x) for x in input().split()]
(ans, n, su, ix, que) = (0, int(input()), 0, 0, [])
a = sorted(map(lambda x, y: (x, y), rints(), rints()))
lst = a[ix][0]
while ix < n:
	while que and a[ix][0] - lst > 1:
		su += heappop(que)
		lst += 1
		ans += su
	lst = a[ix][0]
	while ix < n and a[ix][0] == lst:
		heappush(que, -a[ix][1])
		su += a[ix][1]
		ix += 1
	su += heappop(que)
	ans += su
while que:
	su += heappop(que)
	ans += su
print(ans)


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

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

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect, fractions, statistics
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify, _heapify_max, _heappop_max, nsmallest, nlargest

def main():
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	tc = 1
	for _ in range(tc):
		n = ri()
		a = ria()
		t = ria()
		z = []
		for i in range(n):
			z.append([a[i], t[i]])
		z = sorted(z, key=lambda x: (x[0], -x[1]))
		count = Counter(a)
		nottaken = []
		heapify(nottaken)
		i = 0
		ans = 0
		k = sorted(count.keys())
		prev = k[0]
		t = 0
		ct = 0
		for i in range(len(k)):
			ln = len(nottaken)
			if nottaken:
				for j in range(min(k[i] - prev - 1, ln)):
					g = heappop(nottaken)
					ans += -g[0] * (prev + j + 1 - g[1])
			for j in range(count[k[i]]):
				heappush(nottaken, [-z[ct][1], z[ct][0]])
				ct += 1
			g = heappop(nottaken)
			ans += -g[0] * (k[i] - g[1])
			prev = k[i]
		if nottaken:
			ln = len(nottaken)
			for j in range(ln):
				g = heappop(nottaken)
				ans += -g[0] * (prev + j + 1 - g[1])
		print(ans)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			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, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			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()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

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

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


import sys
from array import array
import typing as Tp

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def main():
	from collections import defaultdict
	from heapq import heappop, heappush
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	dd: Tp.Dict[int, Tp.List[int]] = defaultdict(list)
	for i in range(n):
		dd[a[i]].append(b[i])
	hq = []
	total = 0
	ans = 0
	keys = sorted(dd.keys()) + [2 * 10 ** 9]
	for (x, y) in zip(keys, keys[1:]):
		for val in dd[x]:
			heappush(hq, -val)
			total += val
		for i in range(x, y):
			if not hq:
				break
			total += heappop(hq)
			ans += total
	print(ans)
main()


inf = float('inf')
from heapq import heapify, heappop, heappush
from collections import defaultdict
n = int(input())
lst = list(map(int, input().split(' ')))
tm = list(map(int, input().split(' ')))
l = []
for i in range(n):
	l.append([lst[i], tm[i]])
l.sort()
l.append((10 ** 12, 0))
cnt = 0
prev = 0
now = []
for x in l:
	(a, t) = x
	for ai in range(prev, a):
		if not now:
			break
		(tm, am) = heappop(now)
		tm = 10 ** 5 - tm
		cnt += (ai - am) * tm
	heappush(now, (10 ** 5 - t, a))
	prev = a
print(cnt)


import sys
from collections import defaultdict
from heapq import *
input = sys.stdin.readline
d = defaultdict(list)
n = int(input())
a = list(map(int, input().split()))
t = list(map(int, input().split()))
ans = 0
for i in range(n):
	d[a[i]].append(t[i])
key_heap = list(d.keys())
heapify(key_heap)
s = 0
m_heap = []
while len(key_heap) > 0:
	k = heappop(key_heap)
	s += sum(d[k])
	while len(d[k]) > 0:
		y = d[k].pop()
		heappush(m_heap, -y)
	t = heappop(m_heap)
	s += t
	ans += s
	if s != 0 and k + 1 not in d.keys():
		heappush(key_heap, k + 1)
	del d[k]
print(ans)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
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')
mod = 10 ** 9 + 7
from heapq import *
n = int(input())
d = defaultdict(list)
a = list(map(int, input().split()))
t = list(map(int, input().split()))
ans = 0
for i in range(n):
	heappush(d[a[i]], t[i])
key_heap = list(d.keys())
heapify(key_heap)
s = 0
m_heap = []
while len(key_heap) > 0:
	k = heappop(key_heap)
	s += sum(d[k])
	while len(d[k]) > 0:
		y = heappop(d[k])
		heappush(m_heap, -y)
	t = heappop(m_heap)
	s += t
	ans += s
	if s != 0 and k + 1 not in d.keys():
		heappush(key_heap, k + 1)
	del d[k]
print(ans)


import heapq
from collections import defaultdict

def solve(N, A, T):
	numToConflicts = defaultdict(list)
	for (i, x) in enumerate(A):
		numToConflicts[x].append(i)
	conflictNums = list(numToConflicts.keys())
	heapq.heapify(conflictNums)
	scoot = []
	assigned = 0
	cost = 0
	while assigned != N:
		num = heapq.heappop(conflictNums)
		heapCost = float('-inf')
		if scoot:
			(heapCost, fromNum) = scoot[0]
			heapCost *= -1
		conflictCost = float('-inf')
		indices = []
		if num in numToConflicts:
			indices = numToConflicts[num]
			maxIndex = max(indices, key=lambda i: T[i])
			conflictCost = T[maxIndex]
		if heapCost > conflictCost:
			heapq.heappop(scoot)
			cost += (num - fromNum) * heapCost
		else:
			indices = filter(lambda x: x != maxIndex, indices)
		assigned += 1
		for i in indices:
			heapq.heappush(scoot, (-T[i], num))
		if scoot and (not conflictNums or conflictNums[0] != num + 1):
			heapq.heappush(conflictNums, num + 1)
	return cost
(N,) = map(int, input().split())
A = [int(x) for x in input().split()]
T = [int(x) for x in input().split()]
ans = solve(N, A, T)
print(ans)


from heapq import *
n = int(input())
_a = list(map(int, input().split(' ')))
_t = list(map(int, input().split(' ')))
at = [[0, 0]]
for i in range(n):
	at.append([_a[i], _t[i]])
at.append([int(100000000000.0), 0])
at.sort()
Q = []
s = 0
cost = 0
for i in range(1, n + 2):
	a = at[i - 1]
	b = at[i]
	num = a[0]
	while len(Q) > 0 and num < b[0]:
		s += heappop(Q)
		num += 1
		cost += s
	s += b[1]
	heappush(Q, -b[1])
print(cost)


import sys
input = sys.stdin.readline
import heapq
n = int(input())
x = list(map(int, input().split()))
t = list(map(int, input().split()))
a = []
M = 1000000
for i in range(n):
	a.append(x[i] * M + t[i])
a.sort()
i = 0
ans = 0
while i < n:
	(xi, ti) = divmod(a[i], M)
	j = i + 1
	while j < n:
		(xj, tj) = divmod(a[j], M)
		b = j - i + xi
		if xj >= b:
			break
		j += 1
	j -= 1
	if i < j:
		b = []
		ptr = i
		for target in range(xi, j - i + xi + 1):
			while ptr <= j:
				(xp, tp) = divmod(a[ptr], M)
				if xp <= target:
					heapq.heappush(b, (-tp, xp))
				else:
					break
				ptr += 1
			(tp, xp) = heapq.heappop(b)
			ans += -tp * (target - xp)
	i = j + 1
print(ans)


import heapq
n = int(input())
a = [[] for _ in range(n)]
j = 0
for i in input().strip().split(' '):
	a[j].append(int(i))
	j += 1
j = 0
for i in input().strip().split(' '):
	a[j].append(int(i))
	j += 1
a.sort()
q = []
total = 0
count = 0
last = a[0][0]
heapq.heappush(q, -a[0][1])
count += a[0][1]
for i in a[1:]:
	if i[0] == last:
		heapq.heappush(q, -i[1])
		count += i[1]
	else:
		while q and last < i[0]:
			count += heapq.heappop(q)
			total += max(count, 0)
			if count < 0:
				count = 0
			last += 1
		last = i[0]
		heapq.heappush(q, -i[1])
		count += i[1]
while q:
	count += heapq.heappop(q)
	total += max(count, 0)
	if count < 0:
		count = 0
print(total)


n = int(input())
A = list(map(int, input().split()))
T = list(map(int, input().split()))
import heapq
nums = list(zip(A, T))
nums.sort(key=lambda x: (x[0], -x[1]))
total = 0
res = 0
cur = -1
i = 0
heap = []
while i < n or heap:
	if not heap:
		cur = nums[i][0]
	while i < n and nums[i][0] == cur:
		heapq.heappush(heap, -nums[i][1])
		total += nums[i][1]
		i += 1
	total -= -heapq.heappop(heap)
	res += total
	cur += 1
print(res)


import sys
inp = sys.stdin.readline
input = lambda : inp().strip()

def iin():
	return int(input())

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

def main():
	import heapq as hq
	n = iin()
	a = lin()
	t = lin()
	dc = {}
	for i in range(n):
		try:
			dc[a[i]].append(t[i])
		except:
			dc[a[i]] = [t[i]]
	sa = list(dc.keys())
	sa.sort()
	n = len(sa)
	ch = 0
	pt = sa[ch]
	temp = []
	sm = 0
	ans = 0
	hq.heapify(temp)
	done = 0
	while ch < n:
		pt = sa[ch]
		if len(dc[pt]) > 1 or done:
			a1 = sorted(dc[pt])
			for item in a1:
				hq.heappush(temp, -item)
				sm += item
			x = hq.heappop(temp) * -1
			dc[pt] = [x]
			sm -= x
			while len(temp):
				ans += sm
				pt += 1
				if pt in dc:
					ch += 1
					done = 1
					break
				else:
					x = hq.heappop(temp) * -1
					sm -= x
			else:
				done = 0
		else:
			ch += 1
			done = 0
	print(ans)
main()


import heapq
n = int(input())
l1 = [int(i) for i in input().split()]
l2 = [int(i) for i in input().split()]
l = list(zip(l1, l2))
l.sort(key=lambda x: (x[0], -x[1]))
h = []
curr = l[0][0]
i = 1
res = 0
while i < n:
	while h:
		if curr >= l[i][0] - 1:
			break
		curr += 1
		temp = heapq.heappop(h)
		res += (curr - temp[1]) * -temp[0]
	heapq.heappush(h, [-l[i][1], l[i][0]])
	if curr < l[i][0]:
		curr = l[i][0]
		temp = heapq.heappop(h)
		res += (curr - temp[1]) * -temp[0]
	i += 1
while h:
	curr += 1
	temp = heapq.heappop(h)
	res += (curr - temp[1]) * -temp[0]
print(res)


import sys
from collections import defaultdict
from heapq import heapify, heappush, heappop
n = int(sys.stdin.readline())
a = list(map(int, sys.stdin.readline().split()))
t = list(map(int, sys.stdin.readline().split()))
umap = defaultdict(list)
for i in range(n):
	umap[a[i]].append(t[i])
pq = []
heapify(pq)
heapsum = 0
ans = 0
for num in sorted(set(a)):
	if len(umap[num]) > 1 or len(pq) > 0:
		for val in umap[num]:
			heappush(pq, -1 * val)
			heapsum += val
		heapsum += pq[0]
		heappop(pq)
		temp = num
		while len(pq) > 0:
			temp += 1
			ans += heapsum
			if len(umap[temp]) > 0:
				break
			else:
				heapsum += pq[0]
				heappop(pq)
print(ans)


import sys
input = sys.stdin.readline
import heapq
h = []
n = int(input())
a = [int(x) for x in input().strip().split()]
t = [int(x) for x in input().strip().split()]
for i in range(len(t)):
	a[i] = [a[i], t[i]]
a.sort(key=lambda x: (x[0], -x[1]))
(prev, i, ans) = (a[0][0], 1, 0)
while i < len(a):
	if h:
		if a[i][0] == prev:
			heapq.heappush(h, [-a[i][1], a[i][0]])
			i += 1
		elif a[i][0] == prev + 1:
			heapq.heappush(h, [-a[i][1], a[i][0]])
			p = heapq.heappop(h)
			ans += -p[0] * (prev + 1 - p[1])
			prev = prev + 1
			i += 1
		else:
			p = heapq.heappop(h)
			ans += -p[0] * (prev + 1 - p[1])
			prev = prev + 1
	elif a[i][0] != prev:
		prev = a[i][0]
		i += 1
	else:
		heapq.heappush(h, [-a[i][1], a[i][0]])
		i += 1
while h:
	p = heapq.heappop(h)
	ans += -p[0] * (prev + 1 - p[1])
	prev = prev + 1
print(ans)


import heapq
import sys
input = sys.stdin.buffer.readline

def process(A, T):
	d = {}
	n = len(A)
	for i in range(n):
		a = A[i]
		t = T[i]
		if a not in d:
			d[a] = []
		d[a].append(t)
	curr = []
	curr_S = 0
	m = min(d)
	answer = 0
	L = sorted(d)
	n2 = len(L)
	for i in range(n2):
		m = L[i]
		for x in d[m]:
			curr_S += x
			heapq.heappush(curr, -1 * x)
		while len(curr) > 0 and (i + 1 < n2 and m < L[i + 1] or i == n2 - 1):
			entry = heapq.heappop(curr)
			entry = entry * -1
			curr_S -= entry
			answer += curr_S
			m += 1
	return answer
n = int(input())
A = [int(x) for x in input().split()]
T = [int(x) for x in input().split()]
print(process(A, T))


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 math
import bisect
from collections import Counter
import bisect
from heapq import *
from collections import defaultdict
n = int(input())
arr = list(map(int, input().split()))
ls = list(map(int, input().split()))
d = defaultdict(list)
for i in range(n):
	heappush(d[arr[i]], ls[i])
key_heap = list(d.keys())
heapify(key_heap)
s = 0
ans = 0
m_heap = []
while len(key_heap) > 0:
	curent_key = heappop(key_heap)
	s += sum(d[curent_key])
	while len(d[curent_key]) > 0:
		y = heappop(d[curent_key])
		heappush(m_heap, -y)
	var = heappop(m_heap)
	s += var
	ans += s
	if s != 0 and curent_key + 1 not in d.keys():
		heappush(key_heap, curent_key + 1)
	del d[curent_key]
print(ans)


import collections
union_arr = collections.defaultdict(int)

def func():
	n_cates = int(input())
	cate_i = list(map(int, input().split()))
	time_i = list(map(int, input().split()))
	idx = [index for (index, value) in sorted(list(enumerate(time_i)), reverse=True, key=lambda x: x[1])]
	cate_i = [cate_i[i] for i in idx]
	time_i = [time_i[i] for i in idx]
	ans = 0
	for i in range(n_cates):
		f = find(cate_i[i])
		if f == cate_i[i]:
			union(f, f + 1)
		else:
			union(f, f + 1)
			ans += (f - cate_i[i]) * time_i[i]
	print(ans)

def union(a, b):
	rt_b = find(b)
	if rt_b != a:
		union_arr[a] = rt_b

def find(a):
	if union_arr[a] == 0:
		return a
	union_arr[a] = find(union_arr[a])
	return union_arr[a]
func()


n = int(input())
al = list(map(int, input().split()))
tl = list(map(int, input().split()))
atl = []
for (a, t) in zip(al, tl):
	atl.append((a, -t))
atl = sorted(atl)
kouho = []
import heapq
heapq.heapify(kouho)
ans = 0
s = 0
idx = 0
while True:
	if idx == n:
		while kouho:
			(t1, a1) = heapq.heappop(kouho)
			ans += (s - a1) * t1
			s += 1
		print(-ans)
		exit()
	if atl[idx][0] <= s:
		(a1, t1) = atl[idx]
		heapq.heappush(kouho, (t1, a1))
		idx += 1
		continue
	elif kouho:
		(t1, a1) = heapq.heappop(kouho)
		ans += (s - a1) * t1
		s += 1
	else:
		(a1, t1) = atl[idx]
		heapq.heappush(kouho, (t1, a1))
		idx += 1
		s = a1
		continue


a = int(input())
z = list(map(int, input().split()))
r = list(map(int, input().split()))
ans = []
for i in range(a):
	ans.append([z[i], r[i]])
ans.sort()
from heapq import *
i = 0
pq = []
ss = 0
sol = 0
while i < len(z):
	if len(pq) == 0:
		heappush(pq, -1 * ans[i][1])
		ss += ans[i][1]
		v = ans[i][0]
		i += 1
	while i < len(ans) and ans[i][0] == v:
		heappush(pq, -ans[i][1])
		ss += ans[i][1]
		i += 1
	ss += heappop(pq)
	sol += ss
	v += 1
while pq:
	ss += heappop(pq)
	sol += ss
print(sol)


from sys import stdin, gettrace
from heapq import *
if not gettrace():

	def input():
		return next(stdin)[:-1]

def main():
	n = int(input())
	aa = [int(a) for a in input().split()]
	bb = [int(a) for a in input().split()]
	bss = {}
	aheap = []

	def insert_bss(a, b):
		if a not in bss:
			bss[a] = []
			heappush(aheap, a)
		bss[a].append(b)
	for (a, b) in zip(aa, bb):
		insert_bss(a, b)
	cost = 0
	moving = []
	stepcost = 0
	while aheap:
		a = heappop(aheap)
		if len(bss[a]) > 1:
			bss[a].sort()
			for b in bss[a][:-1]:
				heappush(moving, -b)
				stepcost += b
		cost += stepcost
		if len(moving) > 0:
			bi = -heappop(moving)
			insert_bss(a + 1, bi)
			stepcost -= bi
	print(cost)
main()


import sys
from heapq import heappush, heappop
n = int(input())
a = list(map(int, input().split()))
count = {}
for x in a:
	if x in count:
		count[x] = count[x] + 1
	else:
		count[x] = 1
count = sorted(list(count.items()))
cost = list(map(int, input().split()))
max_cost = max(cost)
a = list(zip(a, cost))
a = sorted(a)
priority = list([max_cost - x for x in [x[1] for x in a]])
a = list(zip(priority, a))
i = 0
queue = []
queue_cost = 0
result = 0
for j in range(len(count)):
	(x, c) = count[j]
	while i < len(a) and a[i][1][0] == x:
		queue_cost += a[i][1][1]
		heappush(queue, a[i])
		i += 1
	y = x
	while len(queue) > 0 and (j == len(count) - 1 or count[j + 1][0] != y):
		popped = heappop(queue)
		queue_cost -= popped[1][1]
		result += queue_cost
		y += 1
print(result)


import os, sys
from io import BytesIO, IOBase
from heapq import *

def main():
	n = int(input())
	lst = [(a, b) for (a, b) in zip(map(int, input().split()), map(int, input().split()))]
	lst.sort(key=lambda xx: xx[0])
	heap = []
	(i, ans, su) = (0, 0, 0)
	while i != n:
		(j, st) = (i, lst[max(0, i - 1)][0])
		ans += su * (lst[i][0] - st)
		for x in range(lst[i][0] - st):
			if not len(heap):
				break
			r = heappop(heap)
			su += r
			ans += r * (lst[i][0] - x - st)
		while i != n and lst[i][0] == lst[j][0]:
			su += lst[i][1]
			heappush(heap, -lst[i][1])
			i += 1
	cou = 0
	while len(heap):
		ans -= cou * heappop(heap)
		cou += 1
	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()


import heapq
n = int(input())
a = [int(x) for x in input().split()]
t = [int(x) for x in input().split()]
at = []
for i in range(n):
	at.append([a[i], t[i]])
at.sort(key=lambda x: x[0])
gp = []
gpSum = 0
size = 0
ans = 0
for i in range(n):
	(a, t) = at[i]
	size = a
	heapq.heappush(gp, -t)
	gpSum += t
	while True:
		if gpSum == 0 or (i + 1 < n and size == at[i + 1][0]):
			break
		if len(gp) > 1:
			ans += gpSum - -gp[0]
		if len(gp) > 0:
			gpSum -= -gp[0]
			heapq.heappop(gp)
		size += 1
print(ans)


from collections import deque, Counter
import array
from itertools import combinations, permutations
from math import sqrt
from heapq import heappush as push, heappop as pop

def read_int():
	return int(input().strip())

def read_int_array():
	return [int(i) for i in input().strip().split(' ')]
n = read_int()
a = read_int_array()
t = read_int_array()
srt = list(sorted(((a[i], t[i]) for i in range(n))))
cnt = [(-srt[0][1], 0)]
i = 1
cntValue = srt[0][0]
ans = 0
while cnt or i < n:
	if i < n and srt[i][0] == cntValue:
		push(cnt, (-srt[i][1], i))
		i += 1
	elif any(cnt):
		(ti, inx) = pop(cnt)
		ti = -ti
		ans += (cntValue - srt[inx][0]) * ti
		cntValue += 1
	else:
		cntValue = srt[i][0]
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')
import heapq
n = int(input())
nums = list(map(int, input().split()))
cost = list(map(int, input().split()))
dict1 = {}
for s in range(n):
	if not nums[s] in dict1:
		dict1[nums[s]] = [cost[s]]
	else:
		dict1[nums[s]].append(cost[s])
nums = set(nums)
nums = list(nums)
nums.sort()
heapy = []
heapq.heapify(heapy)
summy = 0
ans = 0
for s in range(len(nums)):
	if len(heapy) > 0:
		ans += summy
	while len(dict1[nums[s]]) > 0:
		v0 = dict1[nums[s]].pop()
		heapq.heappush(heapy, -v0)
		summy += v0
	v1 = heapq.heappop(heapy)
	dict1[nums[s]].append(-v1)
	summy -= -v1
	if s < len(nums) - 1:
		for b in range(min(nums[s + 1] - 1 - nums[s], len(heapy))):
			ans += summy
			v2 = heapq.heappop(heapy)
			summy -= -v2
	else:
		for b in range(len(heapy)):
			ans += summy
			v2 = heapq.heappop(heapy)
			summy -= -v2
print(ans)


import os
import heapq as hp
import sys, threading
import math as mt
import operator
from copy import copy
from collections import defaultdict, deque
from io import BytesIO, IOBase

def gcd(a, b):
	if b == 0:
		return a
	else:
		return gcd(b, a % b)

def pw(a, b):
	result = 1
	while b > 0:
		if b % 2 == 1:
			result *= a
		a *= a
		b //= 2
	return result

def inpt():
	return [int(k) for k in input().split()]

def main():
	n = int(input())
	ar = inpt()
	time = inpt()
	for i in range(n):
		ar[i] = (ar[i], time[i])
	ar.sort()
	heap = []
	hp.heapify(heap)
	ct = 0
	ans = 0
	for i in range(n):
		(a, b) = ar[i]
		while ct < a and heap:
			(val, pos) = hp.heappop(heap)
			ans += abs(val) * (ct - pos)
			ct += 1
		ct = a
		hp.heappush(heap, (-b, a))
	while heap:
		(val, pos) = hp.heappop(heap)
		ans += abs(val) * (ct - pos)
		ct += 1
	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()


from heapq import *
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def main():
	n = II()
	aa = LI()
	tt = LI()
	at = [(a, t) for (a, t) in zip(aa, tt)]
	heapify(at)
	pen = []
	a = 0
	s = 0
	ans = 0
	while pen or at:
		while not pen or (at and at[0][0] == a):
			(na, nt) = heappop(at)
			heappush(pen, -nt)
			a = na
			s += nt
		t = -heappop(pen)
		s -= t
		ans += s
		a += 1
	print(ans)
main()


import sys
input = sys.stdin.readline
import heapq as hp
N = int(input())
A = list(map(int, input().split()))
T = list(map(int, input().split()))
AT = {}
for (a, t) in zip(A, T):
	if a in AT:
		AT[a].append(t)
	else:
		AT[a] = [t]
As = sorted(list(set(A)))
q = []
S = 0
ans = 0
ind = -1
for a in As:
	while q and ind <= a:
		s = -hp.heappop(q)
		S -= s
		ans += S
		ind += 1
	for t in AT[a]:
		hp.heappush(q, -t)
		S += t
	ind = a + 1
while q:
	s = -hp.heappop(q)
	S -= s
	ans += S
print(ans)


import sys
input = sys.stdin.readline
n = int(input())
raw1 = list(map(int, input().split()))
raw2 = list(map(int, input().split()))
c = []
for i in range(n):
	c.append((raw1[i], raw2[i]))
c.sort()
c.append((10 ** 12, 0))
import heapq
ans = 0
last = 0
now = []
for x in c:
	(a, t) = x
	for ai in range(last, a):
		if not now:
			break
		(tm, am) = heapq.heappop(now)
		tm = 10 ** 5 - tm
		ans += (ai - am) * tm
	heapq.heappush(now, (10 ** 5 - t, a))
	last = a
print(ans)


from bisect import bisect_left as bl, bisect_right as br, insort
import sys
import heapq
from math import *
from collections import defaultdict as dd, deque

def data():
	return sys.stdin.readline().strip()

def mdata():
	return map(int, data().split())
n = int(data())
A = list(mdata())
T = list(mdata())
AT = sorted(list(zip(A, T)), key=lambda x: (x[0], x[1]))
H = []
a = ans = 0
s = 0
for i in AT:
	if i[0] == a:
		heapq.heappush(H, -i[1])
		s += i[1]
	else:
		if H:
			t = heapq.heappop(H)
			s += t
			a += 1
		while H and a != i[0]:
			t = heapq.heappop(H)
			ans += s
			s += t
			a += 1
		ans += s
		heapq.heappush(H, -i[1])
		s += i[1]
		a = i[0]
if H:
	t = heapq.heappop(H)
	s += t
while H:
	t = heapq.heappop(H)
	ans += s
	s += t
print(ans)


n = int(input())
a = [int(i) for i in input().split(' ')]
t = [int(i) for i in input().split(' ')]
import collections
from heapq import heapify, heappop, heappush
l = collections.defaultdict(list)
at = [[a[i], t[i]] for i in range(n)]
at.sort(key=lambda x: x[0])
for (aa, tt) in at:
	l[aa].append(tt)
res = 0
q = sorted(l.keys())[::-1]
tmp = []
heapify(tmp)
sums = 0
while q:
	i = q.pop()
	if len(l[i]) == 1 and (not tmp):
		continue
	else:
		for ll in l[i]:
			heappush(tmp, -ll)
			sums += ll
		idx = i
		while tmp and (q and idx + 1 != q[-1] or not q):
			p = -heappop(tmp)
			res += sums - p
			sums -= p
			idx += 1
		if tmp:
			p = -heappop(tmp)
			res += sums - p
			sums -= p
			if not q:
				q.append(idx + 1)
print(res)


import heapq
n = int(input())
(*a,) = map(int, input().split())
(*t,) = map(int, input().split())
i = 0
sorted_idxs = sorted(range(n), key=lambda o: (a[o], -t[o]))
cur_val = a[sorted_idxs[0]]
dupls = []
ans = 0
s = 0
for (i, idx) in enumerate(sorted_idxs):
	cur_val = a[idx]
	heapq.heappush(dupls, (-t[idx], a[idx]))
	s += t[idx]
	while dupls and (i == len(a) - 1 or cur_val + 1 <= a[sorted_idxs[i + 1]]):
		cur_val += 1
		(largest, a_val) = heapq.heappop(dupls)
		largest *= -1
		s -= largest
		ans += s
print(ans)


import heapq
n = int(input())
A = [int(i) for i in input().split()]
T = [int(i) for i in input().split()]
AT = [A[i] * 10 ** 6 + T[i] for i in range(n)]
AT.sort()
(aa, tt) = (0, 0)
ans = 0
H = []
for at in AT:
	(a, t) = (at // 10 ** 6, at % 10 ** 6)
	if a == aa:
		heapq.heappush(H, -t)
		tt += t
	else:
		while H and aa < a:
			tm = heapq.heappop(H)
			tt += tm
			ans += tt
			aa += 1
		heapq.heappush(H, -t)
		aa = a
		tt += t
while H:
	tm = heapq.heappop(H)
	tt += tm
	ans += tt
print(ans)


import sys
input = sys.stdin.readline
from collections import *
from heapq import *
n = int(input())
a = list(map(int, input().split()))
t = list(map(int, input().split()))
d = defaultdict(list)
for i in range(n):
	d[a[i]].append(t[i])
ks = list(d.keys())
ks.sort()
prev = ks[0]
ans = 0
s = 0
pq = []
for a in ks:
	for _ in range(a - prev - 1):
		if len(pq) == 0:
			break
		ans += s
		s -= -heappop(pq)
	ans += s
	for t in d[a]:
		heappush(pq, -t)
		s += t
	s -= -heappop(pq)
	prev = a
while len(pq):
	ans += s
	s -= -heappop(pq)
print(ans)


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import heapq
n = int(input())
a = list(map(int, input().split()))
t = list(map(int, input().split()))
ua = len(set(a))
if ua == n:
	print(0)
else:
	d = {}
	for i in range(n):
		if a[i] in d:
			d[a[i]].append((-t[i], a[i]))
		else:
			d[a[i]] = [(-t[i], a[i])]
	for i in d:
		heapq.heapify(d[i])
	keys = list(d.keys())
	heapq.heapify(keys)
	cost = 0
	int_heap = []
	while keys:
		key = heapq.heappop(keys)
		vals = []
		if key in d:
			vals = d[key]
			del d[key]
		if int_heap and vals:
			(maxval1, parent1) = heapq.heappop(vals)
			(maxval2, parent2) = heapq.heappop(int_heap)
			if maxval2 < maxval1:
				cost += -maxval2 * (key - parent2)
				heapq.heappush(vals, (maxval1, parent1))
			else:
				cost += -maxval1 * (key - parent1)
				heapq.heappush(int_heap, (maxval2, parent2))
		elif vals:
			(maxval1, parent1) = heapq.heappop(vals)
			cost += -maxval1 * (key - parent1)
		elif int_heap:
			(maxval2, parent2) = heapq.heappop(int_heap)
			cost += -maxval2 * (key - parent2)
		if (vals or int_heap) and key + 1 not in d:
			heapq.heappush(keys, key + 1)
		while vals:
			heapq.heappush(int_heap, vals.pop())
	print(cost)


from heapq import *
n = int(input())
a = list(map(int, input().split()))
t = list(map(int, input().split()))
ls = list(zip(a, t))
ls.sort()
ls.append((10 ** 18, 0))
ans = 0
sm = 0
hq = []
xp = ls[0][0]
heapify(hq)
i = 0
while i <= n:
	if ls[i][0] == xp:
		heappush(hq, -ls[i][1])
		sm += ls[i][1]
		i += 1
	else:
		while hq:
			cnt = heappop(hq)
			cnt = -cnt
			ans += sm - cnt
			sm -= cnt
			xp += 1
			while i <= n:
				if ls[i][0] == xp:
					heappush(hq, -ls[i][1])
					sm += ls[i][1]
				elif ls[i][0] > xp:
					break
				i += 1
		xp = ls[i][0]
print(ans)


import heapq

def metod(x):
	if temp[x] == 'A':
		cursc = a
	else:
		cursc = b
	for i in range(x + 1, len(temp) - 1):
		if temp[i] != temp[i - 1]:
			if temp[i] == 'A':
				cursc += a
			else:
				cursc += b
	return cursc

def morzermorzer():
	n = int(input())
	arr = sorted(list(zip(list(map(int, input().split())), list(map(int, input().split())))))
	(zet, cursc, morzer, answer) = ([], 0, 0, 0)
	while morzer < n:
		temp = arr[morzer][0]
		cursc += arr[morzer][1]
		heapq.heappush(zet, -arr[morzer][1])
		while 0 < n - morzer - 1 and arr[morzer][0] == arr[morzer + 1][0]:
			morzer += 1
			cursc += arr[morzer][1]
			heapq.heappush(zet, -arr[morzer][1])
		if morzer + 1 == n:
			cur = 1e+18
		else:
			cur = arr[morzer + 1][0]
		while zet and temp - cur < 0:
			temp += 1
			cursc += heapq.heappop(zet)
			answer += cursc
		morzer += 1
	print(answer)
morzermorzer()


import heapq
import sys
input = lambda : sys.stdin.readline().strip()
n = int(input())
b = map(int, input().split())
c = map(int, input().split())
d = list(zip(b, c))
d.sort()
h = []
s = 0
i = 0
ans = 0
while i < n:
	lvl = d[i][0]
	s += d[i][1]
	heapq.heappush(h, -d[i][1])
	while i + 1 < n and d[i][0] == d[i + 1][0]:
		i += 1
		s += d[i][1]
		heapq.heappush(h, -d[i][1])
	if i + 1 == n:
		lol = 10000000000000000000
	else:
		lol = d[i + 1][0]
	while h and lvl < lol:
		lvl += 1
		x = heapq.heappop(h)
		s += x
		ans += s
	i += 1
print(ans)


import sys
import heapq
from collections import defaultdict
n = int(sys.stdin.readline())
arr = list(map(int, sys.stdin.readline().split()))
cost = list(map(int, sys.stdin.readline().split()))
for i in range(n):
	arr[i] = [arr[i], cost[i]]
arr.sort()
l = []
heapq.heapify(l)
prev = 0
ans = 0
s = 0
for i in range(n):
	while l and prev < arr[i][0]:
		s -= l[0]
		ans += -s
		prev += 1
		heapq.heappop(l)
	prev = arr[i][0]
	s += -arr[i][1]
	heapq.heappush(l, -arr[i][1])
while l:
	s -= l[0]
	ans += -s
	heapq.heappop(l)
print(ans)


def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z
n = int(input())
l = list(map(int, input().split()))
l1 = list(map(int, input().split()))
l = sort_list(l, l1)
l.reverse()
l1.sort(reverse=True)
f = set()
nextq = dict()
ans = 0

def nex(i):
	if nextq[i] in f:
		nextq[i] = nex(nextq[i])
	return nextq[i]
for i in range(n):
	if l[i] in f:
		d = nex(l[i])
		ans += (d - l[i]) * l1[i]
		f.add(d)
		nextq.update({d: d + 1})
	else:
		f.add(l[i])
		nextq.update({l[i]: l[i] + 1})
print(ans)


import os, sys
from io import IOBase, BytesIO
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			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

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def get_input(a=str):
	return a(input())

def get_int_input():
	return get_input(int)

def get_input_arr(a):
	return list(map(a, input().split()))

def get_int_input_arr():
	return get_input_arr(int)
import heapq as hq
from collections import defaultdict

def solve():
	n = get_int_input()
	s = get_int_input_arr()
	t = get_int_input_arr()
	dc = defaultdict(lambda : [])
	for i in range(len(s)):
		dc[s[i]].append(-1 * t[i])
	s.sort()
	ptr = 0
	res = 0
	while ptr < len(s):
		curr_k = s[ptr]
		if len(dc[curr_k]) > 1:
			st = dc[curr_k]
			sm = -1 * sum(st)
			hq.heapify(st)
			while st:
				mx_ele = hq.heappop(st)
				ptr += 1
				sm = sm - -1 * mx_ele
				res += sm
				curr_k += 1
				for it in dc[curr_k]:
					hq.heappush(st, it)
					sm += -1 * it
		else:
			ptr += 1
	cout << res << endl

def main():
	solve()
main()


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
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 = 1000000007
INF = float('inf')

def main():
	n = N()
	arr = RLL()
	tarr = RLL()
	zp = zip(arr, tarr)
	dic = defaultdict(list)
	odk = sorted(list(set(arr)))
	for (c, t) in zp:
		dic[c].append(t)
	hp = []
	res = sm = 0
	for (i, k) in enumerate(odk):
		nex = odk[i + 1] if i + 1 < len(odk) else float('inf')
		ts = dic[k]
		for t in ts:
			sm += t
			heappush(hp, -t)
		sm += heappop(hp)
		res += sm
		tag = k + 1
		while hp and tag < nex:
			sm += heappop(hp)
			res += sm
			tag += 1
	print(res)
main()


from sys import stdin, stderr

def rl():
	return [int(w) for w in stdin.readline().split()]
(n,) = rl()
a = rl()
t = rl()
from collections import defaultdict
from heapq import *
cd = defaultdict(list)
for (ti, ai) in zip(t, a):
	heappush(cd[ai], -ti)
ch = []
for (a, th) in cd.items():
	heappush(ch, (a, -sum(th), th))
r = 0
while ch:
	(a, ts, th) = heappop(ch)
	mt = heappop(th)
	ts += mt
	r += ts
	if not th:
		continue
	a += 1
	if ch:
		(na, nts, nth) = heappop(ch)
		if na > a:
			heappush(ch, (na, nts, nth))
		else:
			ts += nts
			if len(th) < len(nth):
				(th, nth) = (nth, th)
			for mt in nth:
				heappush(th, mt)
	heappush(ch, (a, ts, th))
print(r)


import sys
import heapq
input = sys.stdin.readline

def read():
	return map(int, input().split())
n = read()
(A, T) = (list(read()), list(read()))
nums = sorted([(val, cost) for (val, cost) in zip(A, T)])
prefix = 0
result = 0
pos = nums[0][0]
index = 0
n = len(A)
q = []
while index < n or q:
	while index < n and nums[index][0] == pos:
		prefix += nums[index][1]
		heapq.heappush(q, -nums[index][1])
		index += 1
	prefix += heapq.heappop(q)
	result += prefix
	if not q:
		if index < n:
			pos = nums[index][0]
	else:
		pos += 1
print(result)


from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
M = mod = 10 ** 9 + 7

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split(' ')]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n').split(' ')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
n = val()
l1 = li()
l2 = li()
d = defaultdict(list)
for i in range(n):
	d[l1[i]].append(l2[i])
cnt = Counter()
curr = l1[0]
l = []
for i in range(n):
	l.append([l1[i], l2[i]])
l.sort(key=lambda x: (x[0], -x[1]))
he = []
i = j = tot = 0
helpd = defaultdict(list)
while i < n:
	tru = 0
	if len(d[l[i][0]]):
		temp = l[i][0]
		while i < n and l[i][0] == temp:
			helpd[-l[i][1]].append(l[i][0])
			heapq.heappush(he, -l[i][1])
			d[l[i][0]].pop()
			i += 1
	else:
		tru = 1
	j = l[i - 1][0] if i < n else l[-1][0]
	while len(he):
		if len(d[j]):
			break
		else:
			temp = heapq.heappop(he)
			tot += -(j - helpd[temp].pop()) * temp
		j += 1
	if tru:
		i += 1
print(tot)


from sys import stdin, stdout
from math import gcd, sqrt, factorial, pi, inf
from collections import deque, defaultdict
from bisect import bisect, bisect_left
from time import time
from itertools import permutations as per
from heapq import heapify, heappush, heappop, heappushpop
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\r\n')
L = lambda : list(R())
P = lambda x: stdout.write(str(x) + '\n')
lcm = lambda x, y: x * y // gcd(x, y)
nCr = lambda x, y: f[x] * inv(f[y] * f[x - y] % N) % N
inv = lambda x: pow(x, N - 2, N)
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7
n = I()
a = sorted(zip(L(), L()))
d = defaultdict(list)
d[a[0][0]] = [a[0][1]]
ex = 0
v = [a[0][0]]
for i in range(1, n):
	if a[i][0] != a[i - 1][0]:
		v.extend([0] * min(ex, a[i][0] - a[i - 1][0] - 1) + [a[i][0]])
		ex -= min(ex, a[i][0] - a[i - 1][0] - 1)
	else:
		ex += 1
	d[a[i][0]] += (a[i][1],)
v.extend([0] * ex)
hp = []
val = defaultdict(list)
ans = 0
for j in range(n):
	if v[j]:
		i = v[j]
		for el in d[i]:
			val[el] += (j,)
			heappush(hp, -el)
	p = -heappop(hp)
	ans += p * (j - val[p].pop())
print(ans)


import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict, deque, Counter
from bisect import *
from math import sqrt, pi, ceil, log, inf
from itertools import permutations
from copy import deepcopy
from heapq import *
from sys import setrecursionlimit

class Data:

	def __init__(self, value):
		self.value = value

	def __lt__(self, other):
		return self.value[0] > other.value[0] or (self.value[0] == other.value[0] and self.value[1] < other.value[1])

def main():
	n = int(input())
	a = list(map(int, input().split()))
	b = defaultdict(list)
	for (i, v) in enumerate(input().split()):
		b[a[i]].append(int(v))
	c = []
	for i in b:
		c.append(i)
	c.sort()
	h = []
	heapify(h)
	m = len(c)
	t = 0
	for i in range(m):
		for j in range(len(b[c[i]])):
			heappush(h, Data((b[c[i]][j], c[i])))
		z = heappop(h).value
		if z[1] != c[i]:
			t += (c[i] - z[1]) * z[0]
		if i + 1 < m:
			if c[i] + 1 != c[i + 1]:
				for j in range(c[i] + 1, min(c[i + 1], c[i] + len(h) + 1)):
					z = heappop(h).value
					t += (j - z[1]) * z[0]
		else:
			for j in range(c[i] + 1, c[i] + len(h) + 1):
				z = heappop(h).value
				t += (j - z[1]) * z[0]
	print(t)
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()


class SegTree:

	def __init__(self, init_val, n, ide_ele, seg_func):
		self.segfunc = seg_func
		self.num = 2 ** (n - 1).bit_length()
		self.ide_ele = ide_ele
		self.seg = [self.ide_ele] * 2 * self.num
		for i in range(n):
			self.seg[i + self.num - 1] = init_val[i]
		for i in range(self.num - 2, -1, -1):
			self.seg[i] = self.segfunc(self.seg[2 * i + 1], self.seg[2 * i + 2])

	def update(self, k, x):
		k += self.num - 1
		self.seg[k] = x
		while k + 1:
			k = (k - 1) // 2
			self.seg[k] = self.segfunc(self.seg[k * 2 + 1], self.seg[k * 2 + 2])

	def query(self, p, q):
		if q <= p:
			return self.ide_ele
		p += self.num - 1
		q += self.num - 2
		res = self.ide_ele
		while q - p > 1:
			if p & 1 == 0:
				res = self.segfunc(res, self.seg[p])
			if q & 1 == 1:
				res = self.segfunc(res, self.seg[q])
				q -= 1
			p = p // 2
			q = (q - 1) // 2
		if p == q:
			res = self.segfunc(res, self.seg[p])
		else:
			res = self.segfunc(self.segfunc(res, self.seg[p]), self.seg[q])
		return res
(N,) = map(int, input().split())
P = list(map(int, input().split()))
T = list(map(int, input().split()))
TT = [(t, i) for (i, t) in enumerate(T)]
TT.sort(key=lambda x: x[0])
j2t = dict()
i2j = dict()
for (j, (t, i)) in enumerate(TT):
	j2t[j + 1] = t
	i2j[i] = j + 1
X = list(zip(P, T))
X = [(p, t, i) for (i, (p, t)) in enumerate(X)]
X.sort(key=lambda x: x[0])
MM = 2 * 10 ** 5 + 1
segtree = SegTree([0] * MM, MM, -1, max)
X.append((10 ** 18, 10 ** 8, N + 1))
b = None
ss = 0
ans = 0
for (p, t, i) in X:
	if b is not None:
		for _ in range(p - b):
			tj = segtree.query(0, MM)
			if tj == 0:
				break
			segtree.update(tj, 0)
			ss -= j2t[tj]
			ans += ss
	if p == 10 ** 18:
		break
	ss += t
	segtree.update(i2j[i], i2j[i])
	b = p
print(ans)


n = int(input())
a = list(map(int, input().split()))
ts = list(map(int, input().split()))
tt = [(ts[i], i) for i in range(n)]
tt.sort(reverse=True)
conflict = {}
next = {}
money = 0

def get_next(i):
	if i not in conflict:
		return i
	if next[i] in conflict:
		next[i] = get_next(next[i])
	return next[i]
for tx in tt:
	(t, i) = tx
	nee = get_next(a[i])
	money += (nee - a[i]) * t
	conflict[nee] = True
	next[nee] = nee + 1
print(money)


from collections import defaultdict
from heapq import heappop, heappush, heapify
n = int(input())
a = list(map(int, input().split()))
t = list(map(int, input().split()))
d = defaultdict(list)
for i in range(n):
	d[a[i]].append(t[i])
heap2 = list(set(a))
heapify(heap2)
ans = 0
used = set()
heap = []
s = 0
while heap2:
	cur = heappop(heap2)
	if cur in used:
		continue
	used.add(cur)
	for ti in d[cur]:
		heappush(heap, -ti)
		s += ti
	ti = -heappop(heap)
	s -= ti
	ans += s
	if heap:
		heappush(heap2, cur + 1)
print(ans)


import sys
from heapq import heappush, heappop

def main():
	n = int(sys.stdin.readline())
	h = sorted(list(zip([int(i) for i in sys.stdin.readline().split()], [int(i) for i in sys.stdin.readline().split()])))
	(z, w, o, res) = ([], 0, 0, 0)
	while o < n:
		t = h[o][0]
		w += h[o][1]
		heappush(z, -1 * h[o][1])
		while 0 < n - o - 1 and h[o][0] == h[o + 1][0]:
			o += 1
			w += h[o][1]
			heappush(z, -1 * h[o][1])
		if o + 1 == n:
			cur = 1e+18
		else:
			cur = h[o + 1][0]
		while z and t - cur < 0:
			t += 1
			w += heappop(z)
			res += w
		o += 1
	print(res)
for test in range(1):
	main()


import heapq as h
from collections import defaultdict
n = int(input())
a = list(map(int, input().split()))
t = list(map(int, input().split()))
d = defaultdict(list)
for i in range(n):
	d[a[i]].append(t[i])
b = list(d.keys())
c = []
sm = 0
h.heapify(b)
ans = 0
while b:
	smallest = h.heappop(b)
	for i in d[smallest]:
		if i == float('inf'):
			continue
		sm += i
		h.heappush(c, -i)
	if c == []:
		continue
	sm += h.heappop(c)
	ans += sm
	if c == []:
		continue
	if smallest + 1 not in d:
		h.heappush(b, smallest + 1)
		d[smallest + 1].append(float('inf'))
	d.pop(smallest)
print(ans)


import heapq
n = int(input())
b = list(map(int, input().split()))
t = list(map(int, input().split()))
sol = 0
x = [(i, j) for (i, j) in zip(b, t)]
x.sort()
ll = []
i = 0
v = 0
ss = 0
while i < len(x):
	if len(ll) == 0:
		heapq.heappush(ll, -x[i][1])
		ss += x[i][1]
		v = x[i][0]
		i += 1
	while i < len(x) and x[i][0] == v:
		heapq.heappush(ll, -x[i][1])
		ss += x[i][1]
		i += 1
	ss += heapq.heappop(ll)
	sol += ss
	v += 1
while ll:
	ss += heapq.heappop(ll)
	sol += ss
print(sol)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
from heapq import *
from math import gcd, factorial, floor, ceil
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
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')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for pp in range(t):
		solve(pp)

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def google(p):
	print('Case #' + str(p) + ': ', end='')

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

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True
inf = pow(10, 20)
mod = 10 ** 9 + 7

def bucketsort(order, seq):
	buckets = [0] * (max(seq) + 1)
	for x in seq:
		buckets[x] += 1
	for i in range(len(buckets) - 1):
		buckets[i + 1] += buckets[i]
	new_order = [-1] * len(seq)
	for i in reversed(order):
		x = seq[i]
		idx = buckets[x] = buckets[x] - 1
		new_order[idx] = i
	return new_order

def ordersort(order, seq, reverse=False):
	bit = max(seq).bit_length() >> 1
	mask = (1 << bit) - 1
	order = bucketsort(order, [x & mask for x in seq])
	order = bucketsort(order, [x >> bit for x in seq])
	if reverse:
		order.reverse()
	return order

def long_ordersort(order, seq):
	order = ordersort(order, [int(i & 2147483647) for i in seq])
	return ordersort(order, [int(i >> 31) for i in seq])

def multikey_ordersort(order, *seqs, sort=ordersort):
	for i in reversed(range(len(seqs))):
		order = sort(order, seqs[i])
	return order

def solve(case):
	n = int(inp())
	l = lis()
	r = lis()
	order = multikey_ordersort(range(n), l, r)
	sl = []
	for i in order:
		sl.append((l[i], r[i]))
	ans = 0
	currsum = 0
	h = []
	for i in range(0, n):
		temp = sl[i][0] - sl[i - 1][0]
		for j in range(temp):
			if len(h) != 0:
				curr = -heappop(h)
				currsum -= curr
				ans += currsum
			else:
				break
		heappush(h, -sl[i][1])
		currsum += sl[i][1]
	while len(h) != 0:
		curr = -heappop(h)
		currsum -= curr
		ans += currsum
	print(ans)
testcase(1)


import time
import os, sys
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import bisect_left, bisect_right
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string, heapq as h
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')

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))

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

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

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

def getStr():
	return input()

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

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

def getBin():
	return list(map(int, list(input())))

def isInt(s):
	return '0' <= s[0] <= '9'

def ceil_(a, b):
	return a // b + (a % b > 0)
MOD = 10 ** 9 + 7

def solve():
	N = getInt()
	A = getInts()
	T = getInts()
	ans = 0
	L = sorted(list(zip(A, T)))
	H = []
	curr_pos = 0
	curr_sum = 0
	idx = -1
	while H or idx < N - 1:
		if not H:
			idx += 1
			curr_pos = L[idx][0]
			h.heappush(H, -L[idx][1])
			curr_sum += L[idx][1]
		while idx + 1 < N and L[idx + 1][0] == curr_pos:
			idx += 1
			h.heappush(H, -L[idx][1])
			curr_sum += L[idx][1]
		curr_sum += h.heappop(H)
		ans += curr_sum
		curr_pos += 1
	return ans
print(solve())


from collections import defaultdict
import heapq
n = int(input())
a = list(map(int, input().split()))
t = list(map(int, input().split()))
d = defaultdict(list)
for i in range(n):
	d[a[i]].append(i)
h_a = list(d.keys())
heapq.heapify(h_a)
h_t = []
time = 0
s = 0
done = set()
while h_a:
	cur_a = heapq.heappop(h_a)
	if cur_a in done:
		continue
	done.add(cur_a)
	for idx in d[cur_a]:
		heapq.heappush(h_t, -t[idx])
		s += t[idx]
	max_t = -heapq.heappop(h_t)
	s -= max_t
	time += s
	if h_t:
		heapq.heappush(h_a, cur_a + 1)
print(time)