Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.

Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).

To reverse the i-th string Vasiliy has to spent c_{i} units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.

String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.

For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.


-----Input-----

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings.

The second line contains n integers c_{i} (0 ≤ c_{i} ≤ 10^9), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. 

Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000.


-----Output-----

If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print  - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent.


-----Examples-----
Input
2
1 2
ba
ac

Output
1

Input
3
1 3 1
aa
ba
ac

Output
1

Input
2
5 5
bbb
aaa

Output
-1

Input
2
3 3
aaa
aa

Output
-1



-----Note-----

In the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.

In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is  - 1.

In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is  - 1.

Difficulty: interview

Starter code:

Solutions:
n = int(input())
c = list(map(int, input().split(" ")))

nodes = dict()
nodes[""] = 0
# print(nodes)
depth = 0

while depth < n:
	# expand
	new_nodes = dict()
	s = input()
	for node in nodes.keys():
		if s >= node:
			# not reverse
			if s in new_nodes:
				new_nodes[s] = min(new_nodes[s], nodes[node])
			else:
				new_nodes[s] = nodes[node]
		if s[::-1] >= node:
			# not reverse
			if s[::-1] in new_nodes:
				new_nodes[s[::-1]] = min(new_nodes[s[::-1]], nodes[node] + c[depth])
			else:
				new_nodes[s[::-1]] = nodes[node] + c[depth]

	nodes = new_nodes
	# print(depth,nodes)
	depth += 1

# print(nodes)
if len(nodes) > 0:
	print(min(nodes.values()))
else:
	print(-1)

import sys
line = sys.stdin.readlines()
n = int(line[0])
c = list(map(int, line[1].split()))

no = (0, '')
yes = (0, '')
for i in range(n):
    s = line[i+2].rstrip('\r\n')
    sr = s[::-1]
    nn, ny, yn, yy = 1e16, 1e16, 1e16, 1e16
    if s >= no[1]:
        nn = no[0]
    if sr >= no[1]:
        ny = no[0] + c[i]
    if s >= yes[1]:
        yn = yes[0]
    if sr >= yes[1]:
        yy = yes[0] + c[i]
    no = (min(nn, yn), s)
    yes = (min(ny, yy), sr)

ans = min(no[0], yes[0])
if ans > 1e15:
    print(-1)
else:
    print(ans)


n = int(input())
e = list(map(int, input().split()))
dp = [[0, 0], [0, 0]]
s_prev = input().strip()
dp[0][1] = e[0]
ans = -1
for i in range(n - 1):
    cur_pos = (i + 1) % 2
    prev_pos = i % 2
    s_cur = input().strip()
    a, b = 0, 0
    if dp[prev_pos][0] != -1 and s_prev <= s_cur:
        a = dp[prev_pos][0]
    else:
        a = -1
    if dp[prev_pos][1] != -1 and s_prev[::-1] <= s_cur:
        b = dp[prev_pos][1]
    else:
        b = -1
    if a == -1 and b == -1:
        dp[cur_pos][0] = -1
    elif a == -1:
        dp[cur_pos][0] = b
    elif b == -1:
        dp[cur_pos][0] = a
    else:
        dp[cur_pos][0] = min(a, b)

    if dp[prev_pos][0] != -1 and s_prev <= s_cur[::-1]:
        a = dp[prev_pos][0] + e[i + 1]
    else:
        a = -1
    if dp[prev_pos][1] != -1 and s_prev[::-1] <= s_cur[::-1]:
        b = dp[prev_pos][1] + e[i + 1]
    else:
        b = -1
    if a == -1 and b == -1:
        dp[cur_pos][1] = -1
    elif a == -1:
        dp[cur_pos][1] = b
    elif b == -1:
        dp[cur_pos][1] = a
    else:
        dp[cur_pos][1] = min(a, b)

    s_prev = s_cur

a = dp[(n + 1) % 2][0]
b = dp[(n + 1) % 2][1]
if a == -1 and b == -1:
    print(-1)
elif a == -1:
    print(b)
elif b == -1:
    print(a)
else:
    print(min(a, b))

#!/usr/bin/env python3

import sys

n = int(input())
c = [int(x) for x in input().split()]
s = [x.strip() for x in sys.stdin.readlines()]
r = [x[::-1] for x in s]

h = [[None, None] for _ in range(n)]

h[0][0] = 0
h[0][1] = c[0]

for i in range(1, n):
    p, q = s[i], s[i][::-1]
    if s[i-1] <= p and h[i-1][0] is not None:
        h[i][0] = h[i-1][0]
    if r[i-1] <= p:
        if h[i-1][1] is not None and (h[i][0] is None or h[i][0] > h[i-1][1]):
            h[i][0] = h[i-1][1]
    if s[i-1] <= q and h[i-1][0] is not None:
        h[i][1] = h[i-1][0] + c[i]
    if r[i-1] <= q:
        if h[i-1][1] is not None and (h[i][1] is None or h[i][1] > h[i-1][1] + c[i]):
            h[i][1] = h[i-1][1] + c[i]

p, q = h[n-1][0], h[n-1][1]
if p is not None and q is not None:
    print(min(p, q))
elif p is not None:
    print(p)
elif q is not None:
    print(q)
else:
    print(-1)


n = int(input())
C = [int(i) for i in input().split()]
inf = sum(C) * 2
ans = inf
a, b = 0, C[0]
prev = input()
rprev = prev[::-1]
for i in range(1, n):
    cur = input()
    rcur = cur[::-1]
    p, q, r, s = inf, inf, inf, inf
    if prev <= cur:
        p = a
    if prev <= rcur:
        q = a + C[i]
    if rprev <= cur:
        r = b
    if rprev <= rcur:
        s = b + C[i]
    a = min(p, r)
    b = min(q, s)
    prev = cur
    rprev = rcur

ans = min(a, b)
if ans == inf:
    print(-1)
else:
    print(ans)


n = int(input())

c = input().split(" ")

for i in range(n):
    c[i] = int(c[i])

norm = ["" for i in range(n)]
rev = ["" for i in range(n)]

for i in range(n):
    norm[i] = input()
    rev[i] = norm[i][::-1]

MAX = 1e18

dp = [[MAX for i in range(2)] for i in range(n)]
dp[0][0] = 0
dp[0][1] = c[0]

for i in range(1, n):
    if norm[i] >= rev[i-1]:
        dp[i][0] = min(dp[i][0], dp[i-1][1])
    if norm[i] >= norm[i-1]:
        dp[i][0] = min(dp[i][0], dp[i-1][0])
    if rev[i] >= rev[i-1]:
        dp[i][1] = min(dp[i][1], dp[i-1][1]+c[i])
    if rev[i] >= norm[i-1]:
        dp[i][1] = min(dp[i][1], dp[i-1][0]+c[i])

ans = min(dp[n-1][0], dp[n-1][1])
if ans == MAX:
    print(-1)
else:
    print(ans)

n = int(input())
c = [int(x) for x in input().split()]
sumc = [0, 0]
lastWord = ['','']
t = [True, True]
newT = [True, True]
newSumc = [0, 0]
for i in range(n):
    s1 = input()
    s = s1
    if (t[0] and (s >= lastWord[0])) and (t[1] and (s >= lastWord[1])):
        newSumc[0] = min(sumc[1], sumc[0])
        newT[0] = True
    elif ((t[0] and (s >= lastWord[0]))):
        newSumc[0] = sumc[0]    
        newT[0] = True
    elif t[1] and (s >= lastWord[1]):
        newSumc[0] = sumc[1]
        newT[0] = True   
    else:
        newT[0] = False
    s2 = s1[::-1]
    s = s2
    if t[0] and (s >= lastWord[0]):
        if t[1] and (s >= lastWord[1]):
            newSumc[1] = min(sumc[0], sumc[1]) + c[i]
        else:
            newSumc[1] = sumc[0] + c[i]
        newT[1] = True
    elif t[1] and (s >= lastWord[1]):
        newSumc[1] = sumc[1] + c[i]
        newT[1] = True
    else:
        newT[1] = False
    lastWord = [s1, s2]
    t[0] = newT[0]
    t[1] = newT[1]
    sumc[0] = newSumc[0]
    sumc[1] = newSumc[1]
    if not(t[0] or t[1]):
        print(-1)
        return
if (t[0] and t[1]):
    print(min(sumc[0],sumc[1]))
elif (t[0]):
    print(sumc[0])
elif (t[1]):
    print(sumc[1])

from sys import stdin, stdout
INF = float('inf')
n = int(stdin.readline())
prices = list(map(int, stdin.readline().split()))
strings = []
for i in range(n):
    strings.append(stdin.readline().strip())
dp = [[INF, INF, INF, INF] for i in range(n)]
for i in range(n - 1):
    if not i:
        if strings[i] <= strings[i + 1]:
            dp[i][0] = 0
        if strings[i][::-1] <= strings[i + 1]:
            dp[i][1] = prices[i]
        if strings[i] <= strings[i + 1][::-1]:
            dp[i][2] = prices[i + 1]
        if strings[i][::-1] <= strings[i + 1][::-1]:
            dp[i][3] = prices[i] + prices[i + 1]
    else:
        if strings[i] <= strings[i + 1]:
            dp[i][0] = min(dp[i - 1][:2])
        if strings[i][::-1] <= strings[i + 1]:
            dp[i][1] = min(dp[i - 1][2:])
        if strings[i] <= strings[i + 1][::-1]:
            dp[i][2] = min(dp[i - 1][:2]) + prices[i + 1]
        if strings[i][::-1] <= strings[i + 1][::-1]:
            dp[i][3] = min(dp[i - 1][2:]) + prices[i + 1]

if min(dp[n - 2]) >= INF:
    stdout.write('-1')
else:
    stdout.write(str(min(dp[n - 2])))

import sys
line = sys.stdin.readlines()
n = int(line[0])
c = list(map(int, line[1].split()))

INF = 1e16
p, pr = '', ''
c0, cr = 0, 0
for i in range(n):
    s = line[i+2].rstrip('\r\n')
    sr = s[::-1]
    c00 = c0 if p  <= s else INF
    cr0 = cr if pr <= s else INF
    c0r = c0 + c[i] if p  <= sr else INF
    crr = cr + c[i] if pr <= sr else INF
    
    p, pr = s, sr
    c0, cr = min(c00, cr0), min(c0r, crr)

ans = min(c0, cr)
if ans >= INF:
    print(-1)
else:
    print(ans)


n = int(input())
N = [0] + list(map(int,input().split()))

S = [[""]*2 for i in range(n + 1)]

for i in range(1, n + 1):
    s = input()
    S[i] = [s, s[::-1]]
    
INF = 10 ** 15

F1 = [[INF] * 2 for i in range(n + 1)]
F2 = [[INF] * 2 for i in range(n + 1)]

F1[1][0] = 0
F1[1][1] = N[1]
F2[1][0] = 0
F2[1][1] = N[1]

for i in range(2, n + 1):
    #print(S[i], S[i -1])
    if S[i][0] >= S[i-1][0] :
        F1[i][0] = min(F1[i-1][0], F2[i-1][0])
        #print('1-- ', i, S[i][0], S[i -1][0], F1[i][0])
 
    if S[i][0] >= S[i-1][1] :
        F2[i][0] = min(F1[i-1][1], F2[i-1][1])
        #print('2-- ', i,  S[i][0], S[i -1][1], F2[i][0])
            
    if S[i][1] >= S[i-1][0]:
        F1[i][1] = min(F1[i-1][0], F2[i-1][0]) + N[i]
        #print('3-- ', i,  S[i][1], S[i -1][0], F1[i][1])
        
    if S[i][1] >= S[i-1][1] :
        F2[i][1] = min(F1[i- 1][1], F2[i-1][1])  + N[i]
        #print(F1[i][1], F2[i-1][1])
        #print('4-- ', i,  S[i][1], S[i -1][1], F2[i][1])
    
#for i in range(n):
#    print('--', F1[i], F2[i])



if min(F1[n][0], F1[n][1], F2[n][0], F2[n][1]) == INF:
    print(-1)
else:
    print(min(F1[n][0], F1[n][1], F2[n][0], F2[n][1]))

def cmp(a, b, c):
    if b == -1:
        return a
    if a == -1 or b + c < a:
        return b + c
    return a

n = int(input())
cs = list(map(int, input().split()))
dp = [[-1, -1] for i in range(n)]

dp[0][0] = 0
dp[0][1] = cs[0]

last = input()
for i in range(1, n):
    s = input()
    rlast = last[::-1]
    rs = s[::-1]

    if s >= last:
        dp[i][0] = cmp(dp[i][0], dp[i-1][0], 0)
    if s >= rlast:
        dp[i][0] = cmp(dp[i][0], dp[i-1][1], 0)
    if rs >= last:
        dp[i][1] = cmp(dp[i][1], dp[i-1][0], cs[i])
    if rs >= rlast:
        dp[i][1] = cmp(dp[i][1], dp[i-1][1], cs[i])
    
    last = s

if dp[n-1][0] == -1:
    print(dp[n-1][1])
elif dp[n-1][1] == -1:
    print(dp[n-1][0])
else:
    print(min(dp[n-1][0], dp[n-1][1]))

n = int(input())

c = [int(s) for s in input().split(" ")]

C_rev = c[0]
C_nrev = 0

last_s = input()
last_s_rev = last_s[::-1]

for i in range(1,n):
    s = input()
    s_rev = s[::-1]
    new_C_nrev = float("inf")
    if last_s <= s:
        new_C_nrev = min(new_C_nrev, C_nrev)
    if last_s_rev <= s:
        new_C_nrev = min(new_C_nrev, C_rev)

    new_C_rev = float("inf")
    if last_s <= s_rev:
        new_C_rev = min(new_C_rev, C_nrev + c[i])
    if last_s_rev <= s_rev:
        new_C_rev = min(new_C_rev, C_rev + c[i])

    if min(C_rev, C_nrev) == float("inf"):
        break

    C_rev = new_C_rev
    C_nrev = new_C_nrev

    last_s = s
    last_s_rev = s_rev

print(-1 if min(C_rev, C_nrev) == float("inf") else min(C_rev, C_nrev))


n = int(input())
c = list(map(int, input().split()))

s1 = ''
s2 = ''
INF = 1e16
c1 = 0
c2 = 0

for i in range(n):
    s = input()
    sr = s[::-1]
    c11 = c1 if s1 <= s else INF
    c21 = c2 if s2 <= s else INF
    c12 = c1+c[i] if s1 <= sr else INF
    c22 = c2+c[i] if s2 <= sr else INF
    s1 = s
    s2 = sr
    c1 = min(c11, c21)
    c2 = min(c12, c22)
    
ans = min(c1, c2)
if ans >= INF:
    print(-1)
else:
    print(ans)


INF = 10**18


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


def main():
    n, = read()
    c = read()

    a = []
    b = []
    for i in range(0, n):
        s = input()
        a.append(s)
        b.append(s[::-1])

    dp = [[0, 0] for _ in range(0, n)]
    dp[0][0] = 0
    dp[0][1] = c[0]

    for i in range(1, n):
        dp[i][0] = INF
        dp[i][1] = INF
        if a[i] >= a[i - 1]:
            dp[i][0] = min(dp[i][0], dp[i - 1][0])
        if a[i] >= b[i - 1]:
            dp[i][0] = min(dp[i][0], dp[i - 1][1])
        if b[i] >= a[i - 1]:
            dp[i][1] = min(dp[i][1], dp[i - 1][0] + c[i])
        if b[i] >= b[i - 1]:
            dp[i][1] = min(dp[i][1], dp[i - 1][1] + c[i])

    res = min(dp[n - 1][0], dp[n - 1][1])
    print(res == INF and -1 or res)

main()

n = int(input())
c = list(map(int,input().split()))
a = []
for _ in range(n):
    a.append(input())

dp = [[1000000000000000000]*2 for x in range(200000)]
#print(dp)
dp[0][0] = 0
dp[0][1] = c[0]

for i in range(1,n):
    if a[i-1] <= a[i] and dp[i-1][0] < dp[i][0]:
        dp[i][0] = dp[i-1][0]
    if a[i-1][::-1] <= a[i] and dp[i-1][1] < dp[i][0]:
        dp[i][0] = dp[i-1][1]
    if a[i-1] <= a[i][::-1] and dp[i-1][0] + c[i] < dp[i][1]:
        dp[i][1] = dp[i-1][0] + c[i]
    if a[i-1][::-1] <= a[i][::-1] and dp[i-1][1] + c[i] < dp[i][1]:
        dp[i][1] = dp[i-1][1] + c[i]


if dp[n-1][0] == 1000000000000000000 and dp[n-1][1] ==1000000000000000000:
    print(-1)
    return
print(min(dp[n-1][0],dp[n-1][1]))


import os, sys, math
from _thread import start_new_thread
from bisect import bisect_right

class pair:
    def __init__(self, a):
        self.first, self.second = a[0], a[1]

def main():
    INF = 10**18
    n = int(input())
    c = list(map(int, input().split()))
    a, b = [], []
    for i in range(n):
        s = input()
        a.append(s)
        b.append(s[::-1])
    dp = [pair([INF, INF]) for i in range(0, n)]
    dp[0].first, dp[0].second = 0, c[0]
    for i in range(1, n):
        dp[i].first = INF
        dp[i].second = INF
        if a[i] >= a[i - 1]:
            dp[i].first = min(dp[i].first, dp[i - 1].first)
        if a[i] >= b[i - 1]:
            dp[i].first = min(dp[i].first, dp[i - 1].second)
        if b[i] >= a[i - 1]:
            dp[i].second = min(dp[i].second, dp[i - 1].first + c[i])
        if b[i] >= b[i - 1]:
            dp[i].second = min(dp[i].second, dp[i - 1].second + c[i])
    res = min(dp[n - 1].first, dp[n - 1].second)
    print([-1, res][res != INF])

def __starting_point():
    return(int(main() or 0))
__starting_point()

import math as m

n = int(input());
cost = list(map(int, input().split()));
s = [];
sr = [];
for i in range(n):
    s.append(list(input()));
    sr.append(list(reversed(s[i])));

dp = [[0, 0] for i in range(n + 1)];
flag = 0;
dp[0][1] = cost[0];
for i in range(1, n):
    if dp[i - 1][0] == -1 and dp[i - 1][1] == -1:
        flag = 1;
        break;

    elif dp[i - 1][0] != -1 and dp[i - 1][1] == -1:
        if s[i] >= s[i - 1]:
            dp[i][0] = dp[i - 1][0];
        else:
            dp[i][0] = -1;
        if sr[i] >= s[i - 1]:
            dp[i][1] = dp[i - 1][0] + cost[i];
        else:
            dp[i][1] = -1;

    elif dp[i - 1][0] == -1 and dp[i - 1][1] != -1:
        if s[i] >= sr[i - 1]:
            dp[i][0] = dp[i - 1][1];
        else:
            dp[i][0] = -1;
        if sr[i] >= sr[i - 1]:
            dp[i][1] = dp[i - 1][1] + cost[i];
        else:
            dp[i][1] = -1;
    else:
        if s[i] >= s[i - 1] and s[i] >= sr[i - 1]:
            dp[i][0] = min(dp[i - 1][0], dp[i - 1][1]);
        elif s[i] >= s[i - 1] and s[i] < sr[i - 1]:
            dp[i][0] = dp[i - 1][0]
        elif s[i] < s[i - 1] and s[i] >= sr[i - 1]:
            dp[i][0] = dp[i - 1][1];
        else:
            dp[i][0] = -1;

        if sr[i] >= s[i - 1] and sr[i] >= sr[i - 1]:
            dp[i][1] = min(dp[i - 1][0], dp[i - 1][1]) + cost[i];
        elif sr[i] >= s[i - 1] and sr[i] < sr[i - 1]:
            dp[i][1] = dp[i - 1][0] + cost[i];
        elif sr[i] < s[i - 1] and sr[i] >= sr[i - 1]:
            dp[i][1] = dp[i - 1][1] + cost[i];
        else:
            dp[i][1] = -1;

if flag == 1:
    print((-1));
else:
    res = max(dp[n - 1][0], dp[n - 1][1]) if min(dp[n - 1][0], dp[n - 1][1]) == -1 else min(dp[n - 1][0], dp[n - 1][1]);
    print(res);



#!/usr/bin/env	python
#-*-coding:utf-8 -*-
n=int(input())
C=tuple(map(int,input().split()))
A=tuple(input()for _ in range(n))
B=tuple(A[i][::-1]for i in range(n))
INF=1<<47
a=0
b=C[0]
for i in range(1,n):
	c=INF if B[i]<A[i-1]else C[i]+a
	if A[i]<A[i-1]:a=INF
	if B[i-1]<=A[i]:a=min(a,b)
	if B[i-1]<=B[i]:c=min(c,C[i]+b)
	b=c
	if INF<=a and INF<=b:break
c=min(a,b)
print(c if INF>c else-1)


#!/usr/bin/env python3.5
import sys

def read_data():
    n = int(next(sys.stdin))
    prices = list(map(int, next(sys.stdin).split()))
    vocabulary = []
    for i in range(n):
        vocabulary.append(next(sys.stdin).strip())
    return n, prices, vocabulary


def apply_op(sNext, sPrev, curCost, optCost):
    if sNext >= sPrev:
        if optCost is None or curCost < optCost:
            return curCost
    return optCost


def solve(n, prices, vocabulary):
    opt_0, opt_1 = 0, prices[0]
    prevStr = vocabulary[0]
    prevStrReversed = "".join(reversed(prevStr))
    for curStr, curPrice in zip(vocabulary[1:], prices[1:]):
        curStrReversed = "".join(reversed(curStr))
        n_opt0, n_opt1 = None, None
        if opt_0 is not None:
            n_opt0 = apply_op(curStr, prevStr, opt_0, n_opt0)
            n_opt1 = apply_op(curStrReversed, prevStr, opt_0 + curPrice, n_opt1)
        if opt_1 is not None:
            n_opt0 = apply_op(curStr, prevStrReversed, opt_1, n_opt0)
            n_opt1 = apply_op(curStrReversed, prevStrReversed, opt_1 + curPrice, n_opt1)
        opt_0, opt_1 = n_opt0, n_opt1
        prevStr, prevStrReversed = curStr, curStrReversed
        if opt_0 is None and opt_1 is None:
            break
    if opt_0 is None:
        return opt_1
    if opt_1 is None:
        return opt_0
    return min(opt_0, opt_1)


def __starting_point():
    n, prices, vocabulary = read_data()
    sorting_cost = solve(n, prices, vocabulary)
    if sorting_cost != None:
        print(sorting_cost)
    else:
        print(-1)

__starting_point()

n=int(input())
c=list(map(int,input().split()))
s=['']*n
INF=int(1e15)
not_rev=[INF]*n
rev=[INF]*n
for i in range(n):
        s[i]=input()
not_rev[0]=0
rev[0]=c[0]
for i in range(1,n):
        if s[i-1]<=s[i]: not_rev[i]=min(not_rev[i],not_rev[i-1])
        if s[i-1][::-1]<=s[i]: not_rev[i]=min(not_rev[i],rev[i-1])
        if s[i-1]<=s[i][::-1]: rev[i]=min(rev[i],not_rev[i-1])
        if s[i-1][::-1]<=s[i][::-1]: rev[i]=min(rev[i],rev[i-1])
        rev[i]+=c[i]
print(-1 if min(rev[n-1],not_rev[n-1])==INF else min(rev[n-1],not_rev[n-1]))


n = int(input())
c = list(map(int, input().split()))
s = []
for _ in range(n):
    s.append(input())
dp = [[float('inf')] * 2 for _ in range(n)]
dp[0][0] = 0
dp[0][1] = c[0]
for i in range(1, n):
    for j in range(2):
        cost = float('inf')
        base_cost = 0
        s_ = s[i]
        if j == 1:
            base_cost = c[i]
            s_ = s_[::-1]
        for k in range(2):
            target_cost = dp[i - 1][k]
            target_s = s[i - 1]
            if k == 1:
                target_s = target_s[::-1]
            if target_s <= s_:
                cost = min(cost, base_cost + target_cost)
            else:
                cost = min(cost, float('inf'))
        dp[i][j] = cost
ans = min(dp[n - 1][0], dp[n - 1][1])
if ans == float('inf'):
    print(-1)
else:
    print(ans)


n = int(input())
c = list(map(int, input().split()))
s = []
for _ in range(n):
    s.append(input())
dp = [[float('inf')] * n for _ in range(2)]
dp[0][0] = 0
dp[1][0] = c[0]
for i in range(1, n):
    for j in range(2):
        cost = float('inf')
        base_cost = 0
        s_ = s[i]
        if j == 1:
            base_cost = c[i]
            s_ = s_[::-1]
        for k in range(2):
            target_cost = dp[k][i - 1]
            target_s = s[i - 1]
            if k == 1:
                target_s = target_s[::-1]
            if target_s <= s_:
                cost = min(cost, base_cost + target_cost)
            else:
                cost = min(cost, float('inf'))
        dp[j][i] = cost
ans = min(dp[0][n - 1], dp[1][n - 1])
if ans == float('inf'):
    print(-1)
else:
    print(ans)



LO_C= 0
LO_S= 1
HI_C= 2
HI_S= 3

def main():
    n = int(input())
    costs = list([int(x) for x in input().split()])
    memo = list()
    for i in range(n):
        s = input().strip()
        r = s[::-1]
        if s <= r:
            lo, lo_c, hi, hi_c = s, 0, r, costs[i]
        else:
            lo, lo_c, hi, hi_c = r, costs[i], s, 0
        if not memo:
            memo.append((lo_c, lo, hi_c, hi))
        else:
            if hi >= memo[-1][LO_S]:
                nxt_hi = hi
                if hi < memo[-1][HI_S] or memo[-1][LO_C] <= memo[-1][HI_C]:
                    nxt_hi_c = hi_c + memo[-1][LO_C]
                else:
                    nxt_hi_c = hi_c + memo[-1][HI_C]
            else:
                return -1;
            if lo >= memo[-1][LO_S]:
                nxt_lo = lo
                if lo < memo[-1][HI_S] or memo[-1][LO_C] <= memo[-1][HI_C]:
                    nxt_lo_c = lo_c + memo[-1][LO_C]
                else:
                    nxt_lo_c = lo_c + memo[-1][HI_C]
            else:
                nxt_lo = nxt_hi
                nxt_lo_c = nxt_hi_c
            memo.append((nxt_lo_c, nxt_lo, nxt_hi_c, nxt_hi))
    return min(memo[-1][LO_C], memo[-1][HI_C])


def __starting_point():
    print(main())

__starting_point()


LO_C= 0
LO_S= 1
HI_C= 2
HI_S= 3

def main():
    n = int(input())
    costs = list([int(x) for x in input().split()])
    memo = list()
    for i in range(n):
        s = input().strip()
        r = s[::-1]
        if s <= r:
            lo, lo_c, hi, hi_c = s, 0, r, costs[i]
        else:
            lo, lo_c, hi, hi_c = r, costs[i], s, 0
        if not memo:
            memo.append((lo_c, lo, hi_c, hi))
        else:
            if hi >= memo[-1][LO_S]:
                nxt_hi = hi
                if hi < memo[-1][HI_S] or memo[-1][LO_C] <= memo[-1][HI_C]:
                    nxt_hi_c = hi_c + memo[-1][LO_C]
                else:
                    nxt_hi_c = hi_c + memo[-1][HI_C]
            else:
                return -1;
            if lo >= memo[-1][LO_S]:
                nxt_lo = lo
                if lo < memo[-1][HI_S] or memo[-1][LO_C] <= memo[-1][HI_C]:
                    nxt_lo_c = lo_c + memo[-1][LO_C]
                else:
                    nxt_lo_c = lo_c + memo[-1][HI_C]
            else:
                nxt_lo = nxt_hi
                nxt_lo_c = nxt_hi_c
            memo.append((nxt_lo_c, nxt_lo, nxt_hi_c, nxt_hi))
    return min(memo[-1][LO_C], memo[-1][HI_C])


def __starting_point():
    print(main())

__starting_point()

def main():
    n, l = int(input()), [(0, "")]
    for c in map(int, input().split()):
        s = input()
        l = [(x + dx, b) for dx, b in ((0, s), (c, s[::-1])) for x, a in l if a <= b]
        l.sort()
        for i in range(len(l) - 1, 0, -1):
            for j in range(i):
                if l[i][1] >= l[j][1]:
                    del l[i]
                    break
    print(min(l)[0] if l else -1)


def __starting_point():
    main()
__starting_point()