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

Starter code:

Solutions:
'''input
3
aa
jj
aa
'''

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)
# print(a)
ans = 0
for i in range(len(a)):
	ans += (i+1)*a[i]
print(ans)				

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)


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]  # reversed
    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))

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)

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)
# print(canzero)
# print(weight)
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(cl, zero, weight)
print(result)


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)



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)

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

    
        
    


# Minimum Sum
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(list(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)


#! /usr/bin/env python3
#------------------------------------------------
# Author:    krishna
# Created:   Sun Dec 24 17:45:40 IST 2017
# File Name: 910c.py
# USAGE:
#       910c.py
# Description:
# 
#------------------------------------------------
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 list(count.items())}

count = {k: int(v / 10) for (k,v) in list(count.items())}

code = {}
counter = 1
zeroUsed = 0

# For given column, fix the values
for k in (sorted(list(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(sorted(code.items()))
print(int(s / 10))


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


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)


ch = ['a','b','c','d','e','f','g','h','i','j']
a = [0]*10 #array to store total decimal value of each element index wise
initial=[] #stores initials of each string
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 #final sum
flag=False #turns true after we have assigned zero
count=1 #digits we assign to each character
for k in range(10):
    maxFreq=0 #stores max value of an char from a array
    for l in range(10): #finds max value from a and assigns it to maxFreq var
        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 #we have assigned this currChar 0 and now we switch flag
    else:
        sum+=maxFreq*count
        count+=1 #1 has been assigned now we assign 2 and so on...
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)


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


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)

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)

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)

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)	

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

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

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)