706C.md (2563B)
1 Source: https://codeforces.com/problemset/problem/706/C 2 3 C. Hard problem 4 5 time limit per test 6 7 1 second 8 9 memory limit per test 10 11 256 megabytes 12 13 input 14 15 standard input 16 17 output 18 19 standard output 20 21 Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help. 22 23 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). 24 25 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. 26 27 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*. 28 29 For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. 30 31 Input 32 33 The first line of the input contains a single integer *n* (2 ≤ *n* ≤ 100 000) — the number of strings. 34 35 The second line contains *n* integers *c**i* (0 ≤ *c**i* ≤ 109), the *i*-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the *i*-th string. 36 37 Then follow *n* lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. 38 39 Output 40 41 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. 42 43 Examples 44 45 Input 46 47 ``` 48 2 49 1 2 50 ba 51 ac 52 ``` 53 54 Output 55 56 ``` 57 1 58 ``` 59 60 Input 61 62 ``` 63 3 64 1 3 1 65 aa 66 ba 67 ac 68 ``` 69 70 Output 71 72 ``` 73 1 74 ``` 75 76 Input 77 78 ``` 79 2 80 5 5 81 bbb 82 aaa 83 ``` 84 85 Output 86 87 ``` 88 -1 89 ``` 90 91 Input 92 93 ``` 94 2 95 3 3 96 aaa 97 aa 98 ``` 99 100 Output 101 102 ``` 103 -1 104 ``` 105 106 Note 107 108 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. 109 110 In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1. 111 112 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.