Petya has n positive integers a_1, a_2, ..., a_{n}. 

His friend Vasya decided to joke and replaced all digits in Petya's numbers with a letters. He used the lowercase letters of the Latin alphabet from 'a' to 'j' and replaced all digits 0 with one letter, all digits 1 with another letter and so on. For any two different digits Vasya used distinct letters from 'a' to 'j'.

Your task is to restore Petya's numbers. The restored numbers should be positive integers without leading zeros. Since there can be multiple ways to do it, determine the minimum possible sum of all Petya's numbers after the restoration. It is guaranteed that before Vasya's joke all Petya's numbers did not have leading zeros.


-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 1 000) — the number of Petya's numbers.

Each of the following lines contains non-empty string s_{i} consisting of lowercase Latin letters from 'a' to 'j' — the Petya's numbers after Vasya's joke. The length of each string does not exceed six characters.


-----Output-----

Determine the minimum sum of all Petya's numbers after the restoration. The restored numbers should be positive integers without leading zeros. It is guaranteed that the correct restore (without leading zeros) exists for all given tests.


-----Examples-----
Input
3
ab
de
aj

Output
47

Input
5
abcdef
ghij
bdef
accbd
g

Output
136542

Input
3
aa
jj
aa

Output
44



-----Note-----

In the first example, you need to replace the letter 'a' with the digit 1, the letter 'b' with the digit 0, the letter 'd' with the digit 2, the letter 'e' with the digit 3, and the letter 'j' with the digit 4. So after the restoration numbers will look like [10, 23, 14]. The sum of them is equal to 47, which is the minimum possible sum of the numbers after the correct restoration.

In the second example the numbers after the restoration can look like: [120468, 3579, 2468, 10024, 3]. 

In the second example the numbers after the restoration can look like: [11, 22, 11].

Difficulty: MEDIUM_HARD
Tags: Greedy algorithms

Mathematics

Constructive algorithms
Skill types: Greedy algorithms

Starter code:

Solutions:
from collections import defaultdict
n = int(input())
aa = [input() for i in range(n)]
counts = defaultdict(int)
canBeZero = set('abcdefghij')
for s in aa:
	canBeZero = canBeZero - {s[0]}
	for (p, d) in enumerate(reversed(s)):
		counts[d] += 10 ** p
sums = sorted([(s, d) for (d, s) in counts.items()], reverse=True)
digits = set(range(0, 10))
res = 0
for (s, dchar) in sums:
	min2 = sorted(digits)[:2]
	index = 0
	if dchar not in canBeZero and min2[0] == 0:
		index = 1
	dig = min2[index]
	digits = digits - {dig}
	res += s * dig
print(res)


b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
l = [0] * 10
z = set()
n = int(input())
for i in range(n):
	s = input()
	z.add(s[0])
	for j in range(len(s)):
		l[b.index(s[j])] += 10 ** (len(s) - j - 1)
s = 0
h = 0
j = 1
notfirst = set(b) - z
for k in range(10):
	ma = 0
	value = 0
	for i in range(10):
		if l[i] > ma:
			ma = l[i]
			value = i
	if b[value] in z or h == 1:
		s += ma * j
		j += 1
	else:
		h = 1
	l[value] = 0
print(s)


from collections import defaultdict
n = int(input())
is_first = []
d = defaultdict(int)
ans = 0
for _ in range(n):
	s = input()
	slen = len(s)
	for i in range(slen):
		t = s[i]
		if i == 0:
			if t not in is_first:
				is_first.append(t)
		num = 10 ** (slen - i - 1)
		d[t] += num
l = sorted(d.items(), key=lambda v: v[1], reverse=True)
for (i, x) in enumerate(l):
	if x[0] not in is_first:
		l.pop(i)
		break
for (i, x) in enumerate(l):
	ans += x[1] * (i + 1)
print(ans)


import sys, operator
data = []
c = int(sys.stdin.readline().rstrip())
for i in range(c):
	data.append(sys.stdin.readline().rstrip())
maxLen = max((len(line) for line in data))
cantTakeZero = [line[0] for line in data]
for i in range(len(data)):
	data[i] = '0' * (maxLen - len(data[i])) + data[i]
count = {chr(i): 0 for i in range(ord('a'), ord('k'))}
for i in range(maxLen):
	for line in data:
		if line[i] == '0':
			continue
		count[line[i]] += 1
	count = {k: v * 10 for (k, v) in count.items()}
count = {k: int(v / 10) for (k, v) in count.items()}
code = {}
counter = 1
zeroUsed = 0
for k in sorted(count.items(), key=operator.itemgetter(1), reverse=True):
	if k[0] in code:
		continue
	if zeroUsed == 0 and (k[0] in cantTakeZero) == False:
		code[k[0]] = 0
		zeroUsed = 1
	else:
		code[k[0]] = counter
		counter += 1
s = 0
for i in range(maxLen):
	for line in data:
		if line[i] != '0':
			s += code[line[i]]
	s *= 10
print(int(s / 10))


alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
mapping = [0] * 10
n = int(input())
firstLetter = []
for i in range(n):
	s = input()
	firstLetter.append(s[0])
	for j in range(len(s)):
		mapping[alphabets.index(s[j])] += 10 ** (len(s) - j - 1)
flow = 1
catchZero = 0
ans = 0
for i in range(10):
	saikyu = 0
	for j in range(10):
		if saikyu < mapping[j]:
			saikyu = mapping[j]
	if alphabets[mapping.index(saikyu)] not in firstLetter and catchZero == 0:
		catchZero = 1
	else:
		ans += saikyu * flow
		flow += 1
	mapping[mapping.index(saikyu)] = 0
print(ans)


from collections import defaultdict
n = int(input())
d = defaultdict(int)
nonzero = set()
for _ in range(n):
	a = input()
	for (i, c) in enumerate(a):
		d[c] += 10 ** (len(a) - i - 1)
		if i == 0:
			nonzero.add(c)
avail = [1, 2, 3, 4, 5, 6, 7, 8, 9]
zeroused = 0
M = {}
for k in sorted(d, key=lambda x: -d[x]):
	if k not in nonzero and (not zeroused):
		M[k] = 0
		zeroused = 1
	else:
		M[k] = avail[0]
		avail.pop(0)
s = 0
for k in d:
	s += d[k] * M[k]
print(s)


from collections import defaultdict
n = int(input())
lead = set()
d = defaultdict(int)
for _ in range(n):
	s = input()
	k = 1
	for ch in s[::-1]:
		d[ch] += k
		k *= 10
	lead.add(s[0])
a = sorted([(x, ch) for (ch, x) in d.items()], reverse=True)
ans = 0
used = False
i = 0
for (x, ch) in a:
	if not used and ch not in lead:
		used = True
	else:
		i += 1
		ans += i * x
print(ans)


n = int(input())
s = []
dp = [[0, i] for i in range(10)]
z = [True for i in range(10)]
for i in range(n):
	s1 = input()
	z[ord(s1[0]) - 97] = False
	s.append(s1)
	for i in range(len(s1)):
		dp[ord(s1[i]) - 97][0] += 10 ** (len(s1) - i)
dp.sort()
dp.reverse()
d = dict()
x = 0
for i in dp:
	if z[i[1]] == True:
		x = i
		break
dp.remove(x)
dp = [x] + dp
y = 0
for i in dp:
	d.update({chr(i[1] + 97): str(y)})
	y += 1
tot = 0
for i in s:
	s2 = ''
	for j in i:
		s2 += d[j]
	tot += int(s2)
print(tot)


n = int(input())
mul = [0] * 10
can_zero = [True] * 10
for i in range(n):
	s = input()
	for j in range(len(s)):
		mul[ord(s[j]) - 97] += 10 ** (len(s) - 1 - j)
	can_zero[ord(s[0]) - 97] = False
(max_zero, max_zero_idx) = (-1, -1)
for i in range(10):
	if can_zero[i]:
		(max_zero, max_zero_idx) = max((max_zero, max_zero_idx), (mul[i], i))
mul[max_zero_idx] = 10 ** 20
mul.sort()
ans = 0
for i in range(10):
	ans += (9 - i) * mul[i]
print(ans)


import string
n = int(input())
L = [0] * 10
leaded = [False] * 10
for i in range(n):
	word = input()
	for i in range(len(word)):
		char = word[-(i + 1)]
		L[ord(char) - ord('a')] += 10 ** i
	leaded[ord(word[0]) - ord('a')] = True
total = 0
index = 1
zeroed = False
while sum(L) > 0:
	t = max(L)
	place = L.index(t)
	if leaded[place] == False and (not zeroed):
		zeroed = True
	else:
		total += index * t
		index += 1
	L[place] = 0
print(total)


n = int(input())
prd = []
adic = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9}
fst = [0] * 10
for i in range(n):
	raw = list(input())
	fst[adic[raw[0]]] = 1
	for i in range(len(raw)):
		prd.append([raw[i], 10 ** (len(raw) - i - 1)])
cnt = [0] * 10
for i in range(len(prd)):
	k = adic[prd[i][0]]
	cnt[k] += prd[i][1]
prt = []
p = 1
for i in range(10):
	if fst[i] == 1:
		prt.append([i, p])
		p += 1
	else:
		pass
cob = []
for i in range(10):
	cob.append([i, cnt[i], fst[i]])
scob = sorted(cob, key=lambda d: d[1], reverse=True)
p = 1
sum = 0
t = 0
for j in range(10):
	if scob[j][2] == 1:
		sum += scob[j][1] * p
		p += 1
	elif scob[j][2] == 0 and t == 0:
		t += 1
		pass
	else:
		sum += scob[j][1] * p
		p += 1
print(sum)


b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
l = [0] * 10
z = []
n = int(input())
for i in range(n):
	s = input()
	z.append(s[0])
	for j in range(len(s)):
		l[b.index(s[j])] += 10 ** (len(s) - j - 1)
s = 0
h = 0
j = 1
for k in range(10):
	ma = 0
	for i in range(10):
		if l[i] > ma:
			ma = l[i]
	bi = b[l.index(ma)]
	l[l.index(ma)] = 0
	if not bi in z and h == 0:
		h = 1
	else:
		s += ma * j
		j += 1
print(s)


n = int(input())
L = []
Startswith = []
for i in range(n):
	L.append(input())
	Startswith.append(L[i][0])
Cases = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
coeff = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in L:
	n = len(i)
	for j in range(n):
		coeff[Cases.index(i[j])] += 10 ** (n - j - 1)
cof = list(coeff)
t = False
k = 0
while len(cof) != 0 and t == False:
	m = max(cof)
	p = cof.index(m)
	if Cases[p] in Startswith:
		cof[p] = -1
	else:
		t = True
		coeff[p] = -1
		Cases[p] = 0
c = max(coeff)
j = 1
while len(coeff) != 0 and c != -1:
	c1 = coeff.index(c)
	coeff[c1] = -1
	Cases[c1] = j
	j += 1
	c = max(coeff)

def convert(ch, Cases):
	n = len(ch)
	s = 0
	for i in range(n):
		s += 10 ** (n - i - 1) * Cases[ord(ch[i]) - 97]
	return s
L = [convert(i, Cases) for i in L]
print(sum(L))


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
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')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n
avl = AvlTree()

class SegmentTree1:

	def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a * a + b * b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] <= key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
n = int(input())
l = []
m = 0
for i in range(n):
	l.append(list(input()))
	m = max(m, len(l[-1]))
count = [0 for i in range(10)]
f = [0 for i in range(10)]
for i in range(n):
	for j in range(len(l[i])):
		f[ord(l[i][0]) - 97] = 1
		count[ord(l[i][j]) - 97] += pow(10, len(l[i]) - j)
r = 0
t = 1
ans = [0] * 10
for i in range(10):
	m = count.index(max(count))
	if f[m] == 1:
		ans[m] = t
		count[m] = -1
		t += 1
	elif r == 0:
		ans[m] = 0
		count[m] = -1
		r = 1
	else:
		ans[m] = t
		count[m] = -1
		t += 1
ans1 = 0
for i in range(n):
	s = ''
	for j in range(len(l[i])):
		s = s + str(ans[ord(l[i][j]) - 97])
	ans1 += int(s)
print(ans1)


n = int(input())
lin = 'abcdefghij'
wei = [[0, False] for i in range(10)]
weig = [i for i in range(10)]
inp = []
for i in range(n):
	inp.append(input())
inp.sort(key=len)
n = len(inp[-1])
for i in inp:
	m = len(i)
	wei[lin.index(i[0])][1] = True
	for j in range(m):
		wei[lin.index(i[j])][0] += 10 ** (m - j - 1)
wei.sort(reverse=True)
ans = 0
for i in wei:
	if i[1] and weig[0] == 0:
		ans += i[0] * weig[1]
		weig.remove(weig[1])
	else:
		ans += i[0] * weig[0]
		weig.remove(weig[0])
print(ans)


n = int(input())
inputs = [input() for _ in range(n)]
sums = {char: 0 for char in 'abcdefghij'}
first_digital = {char: 0 for char in sums.keys()}
chars = {}
for s in inputs:
	l = len(s)
	for i in range(l):
		if i == 0:
			first_digital[s[i]] = True
		sums[s[i]] += 10 ** (l - 1 - i)
import operator
sorted_sums = list(reversed(sorted(sums.items(), key=operator.itemgetter(1))))
val = 1
zero_selected = False
for elem in sorted_sums:
	if elem[1] == 0:
		continue
	if first_digital[elem[0]]:
		chars[elem[0]] = val
		val += 1
	elif not zero_selected:
		chars[elem[0]] = 0
		zero_selected = True
	else:
		chars[elem[0]] = val
		val += 1
min_sum = 0
for elem in sorted_sums:
	if elem[1] == 0:
		continue
	min_sum += chars[elem[0]] * elem[1]
print(min_sum)


from math import inf
z = {}
p = {}
for i in range(97, 97 + 10):
	z[chr(i)] = 0
	p[chr(i)] = -1
n = int(input())
x = []
for i in range(n):
	s = input().strip()[::-1]
	x.append(s)
	for j in range(len(s)):
		z[s[j]] += 10 ** j
		if j == len(s) - 1:
			p[s[j]] = 1
m = -inf
an = 0
xx = [0] * 10
for i in p:
	if p[i] == -1:
		if m < z[i]:
			m = z[i]
			an = i
xx[0] = an
p = []
for i in z:
	if i != an:
		p.append([z[i], i])
p.sort(reverse=True)
cc = 1
for i in p:
	xx[cc] = i[1]
	cc += 1
t = {}
c = 0
for i in xx:
	t[i] = c
	c += 1
an = 0
for i in x:
	c = 0
	for j in i:
		an += pow(10, c) * t[j]
		c += 1
print(an)


n = int(input())
(coef, s) = ([0] * 10, [])
for i in range(n):
	s.append(input())
	p = 1
	for ch in reversed(s[-1]):
		coef[ord(ch) - ord('a')] += p
		p *= 10
dz = [0] * 10
for st in s:
	dz[ord(st[0]) - ord('a')] = 1
best = -1
for i in range(10):
	if not dz[i] and (best == -1 or coef[best] < coef[i]):
		best = i
if best != -1:
	coef[best] = 0
coef.sort(reverse=True)
ans = 0
j = 1
for i in range(10):
	if coef[i] >= 0:
		ans += j * coef[i]
		j += 1
print(ans)


n = int(input())
list1 = [0] * 10
list2 = []
list4 = []
for i in range(0, n, 1):
	x = input()
	m = len(x)
	list2.append(x[0])
	for i in range(0, m, 1):
		list1[ord(x[i]) - 97] += 10 ** (m - i - 1)
for i in range(0, 10, 1):
	list3 = [list1[i], chr(i + 97)]
	list4.append(list3)
set2 = set(list2)
list4.sort(reverse=True)
list5 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
h = 0
for i in range(0, 10, 1):
	if 0 in list5:
		if list4[i][1] not in set2:
			h = h + list4[i][0] * list5[0]
			del list5[0]
		else:
			h = h + list4[i][0] * list5[1]
			del list5[1]
	else:
		h = h + list4[i][0] * list5[0]
		del list5[0]
print(h)


from collections import OrderedDict
num_list = [n for n in range(0, 10)]
n = int(input())
char_priority_dict = {}
zero_is_permitted = {}
inputs = []
for c in 'abcdefghij':
	char_priority_dict[c] = 0
	zero_is_permitted[c] = True
for i in range(n):
	s = input()
	inputs.append(s)
	zero_is_permitted[s[0]] = False
	reversed_s = s[::-1]
	for (j, c) in enumerate(reversed_s):
		char_priority_dict[c] += 10 ** j
char_priority_dict = OrderedDict(sorted(char_priority_dict.items(), key=lambda x: x[1], reverse=True))
char_num_dict = {}
for char in char_priority_dict.keys():
	if 0 in num_list:
		if zero_is_permitted[char]:
			char_num_dict[char] = 0
			num_list.remove(0)
		else:
			char_num_dict[char] = num_list[1]
			num_list.remove(num_list[1])
	else:
		char_num_dict[char] = num_list[0]
		num_list.remove(num_list[0])
keys = ''.join(list(char_num_dict.keys()))
values = ''.join(list(map(str, char_num_dict.values())))
restored_values = []
for s in inputs:
	restored_values.append(int(s.translate(s.maketrans(keys, values))))
print(sum(restored_values))


d = {}
non_zeroes = []
letters = list('abcdefghij')
for letter in letters:
	d[letter] = 0
n = int(input())
for i in range(n):
	s = input()
	j = 1
	for letter in s:
		if j == 1 and letter not in non_zeroes:
			non_zeroes.append(letter)
		d[letter] += 10 ** (len(s) - j)
		j += 1
max = 0
zero = ''
for letter in d.keys():
	if d[letter] > max and letter not in non_zeroes:
		zero = letter
		max = d[letter]
if zero in d.keys():
	d.pop(zero)
sum = 0
num = 1
for item in sorted(d.items(), key=lambda x: -x[1]):
	sum += num * item[1]
	num += 1
print(sum)


ch = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
a = [0] * 10
initial = []
n = int(input())
for i in range(n):
	s = input()
	initial.append(s[0])
	for j in range(len(s)):
		a[ch.index(s[j])] += 10 ** (len(s) - j - 1)
sum = 0
flag = False
count = 1
for k in range(10):
	maxFreq = 0
	for l in range(10):
		if maxFreq < a[l]:
			maxFreq = a[l]
	temp = a.index(maxFreq)
	currChar = ch[temp]
	a[temp] = 0
	if currChar not in initial and (not flag):
		flag = True
	else:
		sum += maxFreq * count
		count += 1
print(sum)


n = int(input())
counts = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0}
can_be_zeros = {'a': True, 'b': True, 'c': True, 'd': True, 'e': True, 'f': True, 'g': True, 'h': True, 'i': True, 'j': True}
for i in range(n):
	line = input()
	len_line = len(line)
	if len_line >= 1:
		can_be_zeros[line[0]] = False
	for j in range(len_line):
		counts[line[j]] += 10 ** (len_line - j - 1)
sorted_counts = sorted(counts, key=counts.get)[::-1]
for i in range(10):
	cur = sorted_counts[i]
	if counts[cur] > 0 and can_be_zeros[cur]:
		counts[cur] = 0
		break
result = 0
factor = 1
for i in range(10):
	cur = sorted_counts[i]
	if counts[cur] > 0:
		result += counts[cur] * factor
		factor += 1
print(result)


from collections import defaultdict
(f, d) = (defaultdict(int) for _ in range(2))
n = int(input())
for _ in range(n):
	i = input()
	f[i[0]] = 1
	for (e, j) in enumerate(i):
		d[j] += 10 ** (len(i) - e - 1)
di = list(sorted(d.items(), key=lambda x: x[1], reverse=True))
z = s = d = 0
for (k, v) in di:
	if not z and (not f[k]):
		z = 1
	else:
		s += (d + 1) * v
		d += 1
print(s)


def sumArr(ax):
	sm = 0
	for i in range(len(ax)):
		sm += 10 ** i * ax[i]
	return sm
n = int(input())
arr = {}
la = 'abcdefghij'
for i in la:
	arr.update({i: {'m': [0, 0, 0, 0, 0, 0], 'not0': False, 'sm': 0}})
while n > 0:
	n -= 1
	x = input()[::-1]
	L = len(x)
	for i in range(L):
		arr[x[i]]['m'][i] += 1
		if i == L - 1:
			arr[x[i]]['not0'] = True
arrF = []
arrT = []
for i in la:
	arr[i]['sm'] = sumArr(arr[i]['m'])
	if arr[i]['not0']:
		arrT.append(arr[i]['sm'])
	else:
		arrF.append(arr[i]['sm'])
arrF = sorted(arrF)
arrT = sorted(arrT)
arrF = arrF[::-1]
arrT = arrT[::-1]
iaT = 0
if len(arrF) > 0:
	iaF = 1
	arrQ = [arrF[0]]
else:
	iaF = 0
	arrQ = [0]
for i in range(9):
	(mF, mT) = (-1, -1)
	if iaT < len(arrT):
		mT = arrT[iaT]
	if iaF < len(arrF):
		mF = arrF[iaF]
	if mF >= mT:
		arrQ.append(mF)
		iaF += 1
	else:
		arrQ.append(mT)
		iaT += 1
sm = 0
for i in range(len(arrQ)):
	sm += arrQ[i] * i
print(sm)


n = int(input())
s = []
for i in range(n):
	s.append(input())
a = [0] * 10
for i in range(n):
	for j in range(len(s[i])):
		a[ord(s[i][j]) - ord('a')] += 10 ** (len(s[i]) - 1 - j)
b = []
for i in range(10):
	b.append((a[i], i))
b.sort()
b.reverse()
c = [0] * 10
for i in range(n):
	c[ord(s[i][0]) - ord('a')] = 1
ans = [-1] * 10
for i in range(10):
	if c[b[i][1]] == 0:
		ans[b[i][1]] = 0
		break
j = 1
res = 0
for i in range(10):
	if ans[b[i][1]] == -1:
		res += b[i][0] * j
		j += 1
print(res)


m = {}
f = {}
for c in 'abcdefghij':
	m[c] = f[c] = 0
n = int(input())
for _ in range(n):
	s = input()
	l = len(s)
	f[s[0]] = 1
	for (i, c) in enumerate(s):
		m[c] += 10 ** (l - 1 - i)
ans = 0
d = 1
z = 1
for (c, k) in sorted(m.items(), key=lambda x: x[1], reverse=True):
	if z and (not f[c]):
		z = 0
	else:
		ans += d * k
		d += 1
print(ans)


n = int(input())
tot = {}
nonZero = {}
for i in range(10):
	c = chr(i + ord('a'))
	tot[c] = 0

def processNum(n):
	l = len(n)
	cur = 1
	for i in range(l - 1, -1, -1):
		tot[n[i]] += cur
		cur *= 10
	nonZero[n[0]] = True
for i in range(n):
	n = input()
	processNum(n)
arr = []
for key in tot.keys():
	arr.append([tot[key], key])
arr.sort()
arr.reverse()
for i in range(len(arr)):
	if arr[i][1] not in nonZero:
		del arr[i]
		break
ans = 0
for i in range(len(arr)):
	ans += (i + 1) * arr[i][0]
print(ans)


from collections import defaultdict
n = int(input())
nums = []
digits = defaultdict(int)
heads = set()
for i in range(n):
	nums.append(input())
	w = 1
	heads.add(nums[-1][0])
	for c in range(len(nums[-1]), 0, -1):
		digits[nums[-1][c - 1]] += w
		w *= 10
matching_digits = {}
result = sorted(digits.items(), key=lambda i: i[1])
matching_digits[result[-1][0]] = 1
for i in range(len(result) - 1, 0, -1):
	if result[i - 1][0] not in heads:
		matching_digits[result[i - 1][0]] = 0
		break
v = 2
for i in range(len(result) - 1, 0, -1):
	if not result[i - 1][0] in matching_digits:
		matching_digits[result[i - 1][0]] = v
		v += 1
sum = 0
for num in nums:
	sum += int(''.join((str(matching_digits[c]) for c in num)))
print(sum)


num = []
for i in range(10):
	num.append([])
	num[i].append(1)
	num[i].append(0)
n = int(input())
for kk in range(n):
	s = input()
	num[ord(s[0]) - 97][0] = 0
	for i in range(len(s)):
		num[ord(s[i]) - 97][1] += pow(10, len(s) - i - 1)
num = sorted(num, key=lambda s: s[1], reverse=True)
boo = True
ans = 0
now = 1
for i in range(10):
	if boo and num[i][0] == 1:
		ans += 0
		boo = False
	else:
		ans += num[i][1] * now
		now += 1
print(ans)


import re
import sys
exit = sys.exit
from bisect import bisect_left as bsl, bisect_right as bsr
from collections import Counter, defaultdict as ddict, deque
from functools import lru_cache
cache = lru_cache(None)
from heapq import *
from itertools import *
from math import inf
from pprint import pprint as pp
enum = enumerate
ri = lambda : int(rln())
ris = lambda : list(map(int, rfs()))
rln = sys.stdin.readline
rl = lambda : rln().rstrip('\n')
rfs = lambda : rln().split()
mod = 1000000007
d4 = [(0, -1), (1, 0), (0, 1), (-1, 0)]
d8 = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
n = ri()
a = [rl() for _ in range(n)]
first = set()
cnt = ddict(int)
for s in a:
	first.add(s[0])
	p = 1
	for c in reversed(s):
		cnt[c] += p
		p *= 10
mp = {}
z = 0
v = 1
for c in sorted(cnt, key=lambda c: -cnt[c]):
	if not z and c not in first:
		mp[c] = 0
		z = 1
	else:
		mp[c] = v
		v += 1
ans = 0
for s in a:
	v = 0
	for c in s:
		v = 10 * v + mp[c]
	ans += v
print(ans)


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

def map_input():
	return map(int, input().split())

def map_string():
	return input().split()
n = int(input())
d = {}
pos = {}
for _ in range(n):
	s = list(input())
	s = s[::-1]
	for i in range(len(s)):
		try:
			d[s[i]] += 10 ** i
		except:
			d[s[i]] = 10 ** i
			pos[s[i]] = True
		if i == len(s) - 1:
			pos[s[i]] = False
a = []
b = []
for i in d:
	a.append(d[i])
	if pos[i]:
		b.append(d[i])
if len(b):
	a.remove(max(b))
a.sort(reverse=True)
ans = 0
for i in range(len(a)):
	ans += (i + 1) * a[i]
print(ans)


n = int(input())
d = [0] * (ord('j') + 1)
fr = [0] * (ord('j') + 1)
ans = 0
for i in range(n):
	s = input()
	fr[ord(s[0])] = 1
	for j in range(len(s)):
		d[ord(s[j])] += 10 ** (len(s) - j - 1)
a = [(d[i], i) for i in range(len(d))]
a.sort(reverse=True)
(cr, f) = (1, 1)
for (c, i) in a:
	if f and (not fr[i]):
		f = 0
	else:
		ans += cr * c
		cr += 1
print(ans)


from collections import Counter
inp = [input() for _ in range(int(input()))]
weight = Counter()
for word in inp:
	len_w = len(word) - 1
	for (i, l) in enumerate(word):
		weight[l] += 10 ** (len_w - i)
digit_map = {ord(x): 0 for x in weight}
non_start = set(weight) - {x[0] for x in inp}
if non_start:
	most_nonstart = max(non_start, key=weight.get)
	digit_map[ord(most_nonstart)] = '0'
	del weight[most_nonstart]
digit_ord = (ord(k) for (k, v) in weight.most_common())
for (i, w) in enumerate(digit_ord, ord('1')):
	digit_map[w] = i
print(sum((int(x.translate(digit_map)) for x in inp)))


n = int(input())
ws = [input() for i in range(n)]
X = lambda c: ord(c) - ord('a')
(lead, total) = ([False] * 10, [0] * 10)
for w in ws:
	lead[X(w[0])] = True
	l = len(w)
	for i in range(len(w)):
		total[X(w[i])] += 10 ** (l - i - 1)
(lead, total) = zip(*sorted(zip(lead, total), key=lambda x: -x[1]))
(a, z, s) = (1, True, 0)
for i in range(10):
	if z and (not lead[i]):
		z = False
		continue
	s += a * total[i]
	a += 1
print(s)


mat = []
for i in range(10):
	l = [0 for i in range(10)]
	mat.append(l)
	l = []
verif = [True for i in range(10)]
find = [False for i in range(10)]
s = []
n = int(input())
for i in range(n):
	p = input()
	for j in range(len(p)):
		g = 6 - len(p)
		mat[ord(p[j]) - 97][g + j] += 1
		find[ord(p[j]) - 97] = True
	verif[ord(p[0]) - 97] = False
for i in range(10):
	if find[i] == True:
		u = 0
		for j in range(6):
			u = u + mat[i][j] * 10 ** (5 - j)
		s.append((u, i, verif[i]))
s = sorted(s)
s = s[::-1]
pos = 0
for i in range(len(s)):
	if verif[s[i][1]] == True:
		pos = i
		break
somme = 0
k = 1
r = True
for i in range(len(s)):
	if s[i][2] == True and r == True:
		r = False
	else:
		somme = somme + k * s[i][0]
		k = k + 1
print(somme)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
import threading
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')
n = int(input())
d = [0] * (ord('j') + 1)
fr = [0] * (ord('j') + 1)
ans = 0
for i in range(n):
	s = input()
	fr[ord(s[0])] = 1
	for j in range(len(s)):
		d[ord(s[j])] += 10 ** (len(s) - j - 1)
a = [(d[i], i) for i in range(len(d))]
a.sort(reverse=True)
(cr, f) = (1, 1)
for (c, i) in a:
	if f and (not fr[i]):
		f = 0
	else:
		ans += cr * c
		cr += 1
print(ans)


from collections import defaultdict
n = int(input())
d = defaultdict(int)
cantbezero = set()
for i in range(n):
	s = input()
	cantbezero.add(s[0])
	LEN = len(s)
	mul = 1
	for i in range(LEN - 1, -1, -1):
		d[s[i]] += mul
		mul *= 10
done = defaultdict(int)
arr = []
for key in d.keys():
	arr.append([d[key], key])
arr.sort(reverse=True)
for i in range(len(arr)):
	if arr[i][1] not in cantbezero:
		done[arr[i][1]] = 1234
		break
give = 1
for i in range(len(arr)):
	if not done[arr[i][1]]:
		done[arr[i][1]] = give
		give += 1
ans = 0
for key in d.keys():
	if done[key] != 1234:
		ans += d[key] * done[key]
print(ans)


from pip._vendor.distlib.compat import raw_input
n = int(input())
nuly = [0] * 10
cisla = [0] * 10
for i in range(10):
	cisla[i] = [0, 0]
prirazeni = [0] * 10
je_nula_prirazena = False
for i in range(n):
	vstup = raw_input()
	cisla[ord(vstup[0]) - 97][1] = -1
	for j in range(len(vstup)):
		cisla[ord(vstup[j]) - 97][0] += 10 ** (len(vstup) - j - 1)
cisla.sort(reverse=True)
minimum = 1
for i in range(10):
	if je_nula_prirazena == False:
		if cisla[i][1] == 0:
			prirazeni[i] = 0
			je_nula_prirazena = True
			continue
	prirazeni[i] = minimum
	minimum += 1
print(sum((prirazeni[i] * cisla[i][0] for i in range(10))))


from collections import OrderedDict
n = int(input())
notZeroes = set()
letters = {}
for i in range(n):
	s = input()
	n = len(s)
	notZeroes.add(s[0])
	for char in s:
		n -= 1
		if char in letters:
			letters[char] += 10 ** n
		else:
			letters[char] = 10 ** n
ans = 0
meh = OrderedDict(sorted(letters.items(), key=lambda t: t[1], reverse=True))
mult = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
n = 9
for let in meh.items():
	if let[0] in notZeroes and mult[n] == 0:
		multiplier = mult.pop(n - 1)
	else:
		multiplier = mult.pop()
	ans += let[1] * multiplier
	n -= 1
print(ans)


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
v = [0] * 26
p = [0] * 26
for i in range(I()):
	s = S()[::-1]
	p[ord(s[-1]) - 97] = 1
	for (i, j) in enumerate(s):
		v[ord(j) - 97] += 10 ** i
v = sorted(enumerate(v), reverse=True, key=lambda x: x[1])
a = list(range(27))[::-1]
ans = 0
for (i, j) in v:
	if p[i]:
		if not a[-1]:
			ans += j * a.pop(-2)
		else:
			ans += j * a.pop()
	else:
		ans += j * a.pop()
print(ans)


import math
import operator
num = int(input())
total = 0
store = {}
nonzero = []
_max = 0
for i in range(num):
	_in = input()
	if _max < len(_in):
		_max = len(_in)
	if _in[0] not in nonzero:
		nonzero.append(_in[0])
	for j in range(len(_in) - 1, -1, -1):
		if _in[j] in store:
			store[_in[j]] += pow(10, len(_in) - j - 1)
		else:
			store[_in[j]] = pow(10, len(_in) - j - 1)
x = store
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
used = False
cur = 1
for i in range(len(sorted_x) - 1, -1, -1):
	if sorted_x[i][0] not in nonzero and used == False:
		used = True
	else:
		total += sorted_x[i][1] * cur
		cur += 1
print(total)


from collections import defaultdict
from operator import itemgetter
n = int(input())
nums = [input() for _ in range(n)]
s = defaultdict(int)
first = set()
for num in nums:
	acc = 10 ** (len(num) - 1)
	first.add(num[0])
	for letter in num:
		s[letter] += acc
		acc /= 10
s = list(s.items())
s = sorted(s, key=itemgetter(1), reverse=True)
output = 0
zero = False
idx = 1
for (letter, val) in s:
	if not zero and letter not in first:
		zero = True
	else:
		output += idx * val
		idx += 1
print(int(output))


d = {}
f = {}
p = {}
n = int(input())
for i in range(n):
	l = input()
	f[l[0]] = 1
	t = 0
	for x in range(len(l) - 1, -1, -1):
		if l[x] in d:
			d[l[x]] += 10 ** t
		else:
			d[l[x]] = 10 ** t
		t += 1
y = list(d.items())
l = y[:]
y.sort(reverse=True, key=lambda x: x[1])
for (a, b) in y:
	if a not in f:
		p[a] = '0'
		y.remove((a, b))
		break
t = '123456789'
q = 0
for (a, b) in y:
	p[a] = t[q]
	q += 1

def f(m):
	return p[m]
qa = []
for (a, b) in l:
	w = int(f(a)) * b
	qa.append(w)
print(sum(qa))


n = int(input())
result = 0
weight = [0 for i in range(10)]
canzero = [True for i in range(10)]
for _ in range(n):
	x = list(str(input()))
	canzero[ord(x[0]) - 97] = False
	x.reverse()
	for i in range(len(x)):
		weight[ord(x[i]) - 97] += pow(10, i)
zero = 10
cl = weight[:]
while True:
	candidate = max(cl)
	i = cl.index(candidate)
	if canzero[i]:
		zero = i
		break
	else:
		cl[i] = -1
weight.remove(weight[zero])
weight = sorted(weight)
weight.reverse()
for i in range(1, 10):
	result += i * weight[i - 1]
print(result)