Problem:
Score : 600 points

Problem Statement

We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N.

Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice.

The cost of using the string S_i once is C_i, and the cost of using it multiple times is C_i multiplied by that number of times.

Find the minimum total cost needed to choose strings so that Takahashi can make a palindrome.

If there is no choice of strings in which he can make a palindrome, print -1.

Constraints

1 \leq N \leq 50

1 \leq |S_i| \leq 20

S_i consists of lowercase English letters.

1 \leq C_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
S_1 C_1
S_2 C_2
:
S_N C_N

Output

Print the minimum total cost needed to choose strings so that Takahashi can make a palindrome, or -1 if there is no such choice.

Sample Input 1

3
ba 3
abc 4
cbaa 5

Sample Output 1

7

We have ba, abc, and cbaa.

For example, we can use ba once and abc once for a cost of 7, then concatenate them in the order abc, ba to make a palindrome.
Also, we can use abc once and cbaa once for a cost of 9, then concatenate them in the order cbaa, abc to make a palindrome.

We cannot make a palindrome for a cost less than 7, so we should print 7.

Sample Input 2

2
abcab 5
cba 3

Sample Output 2

11

We can choose abcab once and cba twice, then concatenate them in the order abcab, cba, cba to make a palindrome for a cost of 11.

Sample Input 3

4
ab 5
cba 3
a 12
ab 10

Sample Output 3

8

We can choose a once, which is already a palindrome, but it is cheaper to concatenate ab and cba.

Sample Input 4

2
abc 1
ab 2

Sample Output 4

-1

We cannot make a palindrome, so we should print -1.

Solution in C# (.NET Core 3.1.201) (judge verdict: Runtime Error)

#region いつもの
using AtCoderProject;
using System;
using System.Collections.Generic;
using System.Linq;
using static AtCoderProject.Global;
using BigInteger = System.Numerics.BigInteger;
using BitOperations = System.Numerics.BitOperations;
using IEnumerable = System.Collections.IEnumerable;
using IEnumerator = System.Collections.IEnumerator;
using StringBuilder = System.Text.StringBuilder;
using Unsafe = System.Runtime.CompilerServices.Unsafe;

namespace AtCoderProject { using System.IO; using System.Text; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Linq.Expressions; public static class Global { public static T[] NewArray<T>(int len0, T value) => new T[len0].Fill(value); public static T[] NewArray<T>(int len0, Func<T> factory) { var arr = new T[len0]; for (int i = 0; i < arr.Length; i++) arr[i] = factory(); return arr; } public static T[][] NewArray<T>(int len0, int len1, T value) where T : struct { var arr = new T[len0][]; for (int i = 0; i < arr.Length; i++) arr[i] = NewArray(len1, value); return arr; } public static T[][] NewArray<T>(int len0, int len1, Func<T> factory) { var arr = new T[len0][]; for (int i = 0; i < arr.Length; i++) arr[i] = NewArray(len1, factory); return arr; } public static T[][][] NewArray<T>(int len0, int len1, int len2, T value) where T : struct { var arr = new T[len0][][]; for (int i = 0; i < arr.Length; i++) arr[i] = NewArray(len1, len2, value); return arr; } public static T[][][] NewArray<T>(int len0, int len1, int len2, Func<T> factory) { var arr = new T[len0][][]; for (int i = 0; i < arr.Length; i++) arr[i] = NewArray(len1, len2, factory); return arr; } public static T[][][][] NewArray<T>(int len0, int len1, int len2, int len3, T value) where T : struct { var arr = new T[len0][][][]; for (int i = 0; i < arr.Length; i++) arr[i] = NewArray(len1, len2, len3, value); return arr; } public static T[][][][] NewArray<T>(int len0, int len1, int len2, int len3, Func<T> factory) { var arr = new T[len0][][][]; for (int i = 0; i < arr.Length; i++) arr[i] = NewArray(len1, len2, len3, factory); return arr; } public static long Pow(long x, int y) { long res = 1; for (; y > 0; y >>= 1) { if ((y & 1) == 1) res *= x; x *= x; } return res; } public static BigInteger ParseBigInteger(ReadOnlySpan<char> s) { /* 自前実装の方が速い */ BigInteger res; if (s.Length % 9 == 0) res = 0; else { res = new BigInteger(int.Parse(s.Slice(0, s.Length % 9))); s = s.Slice(s.Length % 9); } while (s.Length > 0) { var sp = s.Slice(0, 9); res *= 1000_000_000; res += int.Parse(sp); s = s.Slice(9); } return res; } public static int PopCount(int x) => BitOperations.PopCount((uint)x); public static int PopCount(long x) => BitOperations.PopCount((ulong)x); public static int PopCount(ulong x) => BitOperations.PopCount(x); public static int MSB(int x) => BitOperations.Log2((uint)x); public static int MSB(uint x) => BitOperations.Log2(x); public static int MSB(long x) => BitOperations.Log2((ulong)x); public static int MSB(ulong x) => BitOperations.Log2(x); public static int LSB(int x) => BitOperations.TrailingZeroCount((uint)x); public static int LSB(uint x) => BitOperations.TrailingZeroCount(x); public static int LSB(long x) => BitOperations.TrailingZeroCount((ulong)x); public static int LSB(ulong x) => BitOperations.TrailingZeroCount(x); } public static class Ext { public static bool UpdateMax<T>(this ref T r, T val) where T : struct, IComparable<T> { if (r.CompareTo(val) < 0) { r = val; return true; } return false; } public static bool UpdateMin<T>(this ref T r, T val) where T : struct, IComparable<T> { if (r.CompareTo(val) > 0) { r = val; return true; } return false; } public static long ToLong(this int i) => i; public static T[] Fill<T>(this T[] arr, T value) { Array.Fill(arr, value); return arr; } public static T[] Sort<T>(this T[] arr) { Array.Sort(arr); return arr; } public static string[] Sort(this string[] arr) => Sort(arr, StringComparer.OrdinalIgnoreCase); public static T[] Sort<T, U>(this T[] arr, Expression<Func<T, U>> selector) where U : IComparable<U> => Sort(arr, ExComparer<T>.CreateExp(selector)); public static T[] Sort<T>(this T[] arr, Comparison<T> comparison) { Array.Sort(arr, comparison); return arr; } public static T[] Sort<T>(this T[] arr, IComparer<T> comparer) { Array.Sort(arr, comparer); return arr; } public static T[] Reverse<T>(this T[] arr) { Array.Reverse(arr); return arr; } public static (int index, T max) MaxBy<T>(this T[] arr) where T : IComparable<T> { T max = arr[0]; int maxIndex = 0; for (int i = 0; i < arr.Length; i++) { if (max.CompareTo(arr[i]) < 0) { max = arr[i]; maxIndex = i; } } return (maxIndex, max); } public static (TSource item, TMax max) MaxBy<TSource, TMax>(this IEnumerable<TSource> source, Func<TSource, TMax> maxBySelector) where TMax : IComparable<TMax> { TMax max; TSource maxByItem; var e = source.GetEnumerator(); e.MoveNext(); maxByItem = e.Current; max = maxBySelector(maxByItem); while (e.MoveNext()) { var item = e.Current; var next = maxBySelector(item); if (max.CompareTo(next) < 0) { max = next; maxByItem = item; } } return (maxByItem, max); } public static (int index, T min) MinBy<T>(this T[] arr) where T : IComparable<T> { T min = arr[0]; int minIndex = 0; for (int i = 0; i < arr.Length; i++) { if (min.CompareTo(arr[i]) > 0) { min = arr[i]; minIndex = i; } } return (minIndex, min); } public static (TSource item, TMin min) MinBy<TSource, TMin>(this IEnumerable<TSource> source, Func<TSource, TMin> minBySelector) where TMin : IComparable<TMin> { TMin min; TSource minByItem; var e = source.GetEnumerator(); e.MoveNext(); minByItem = e.Current; min = minBySelector(minByItem); while (e.MoveNext()) { var item = e.Current; var next = minBySelector(item); if (min.CompareTo(next) > 0) { min = next; minByItem = item; } } return (minByItem, min); } public static IComparer<T> Reverse<T>(this IComparer<T> comparer) => Comparer<T>.Create((x, y) => comparer.Compare(y, x)); public static Dictionary<TKey, int> GroupCount<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) => source.GroupBy(keySelector).ToDictionary(g => g.Key, g => g.Count()); public static Dictionary<TKey, int> GroupCount<TKey>(this IEnumerable<TKey> source) => source.GroupCount(i => i); public static Span<T> AsSpan<T>(this List<T> list, int start = 0) => Unsafe.As<Tuple<T[]>>(list).Item1.AsSpan(start, list.Count); public static ref T Get<T>(this T[] arr, int index) { if (index < 0) return ref arr[arr.Length + index]; return ref arr[index]; } public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> dic, TKey key) { dic.TryGetValue(key, out var v); return v; } public static TValue GetOrInit<TKey, TValue>(this IDictionary<TKey, TValue> dic, TKey key, TValue value) { if (dic.TryGetValue(key, out var v)) return v; return dic[key] = value; } } public static class ExComparer<T> { class ExpressionComparer<K> : IComparer<T> where K : IComparable<K> { private class ParameterReplaceVisitor : ExpressionVisitor { private readonly ParameterExpression from; private readonly ParameterExpression to; public ParameterReplaceVisitor(ParameterExpression from, ParameterExpression to) { this.from = from; this.to = to; } protected override Expression VisitParameter(ParameterExpression node) => node == from ? to : base.VisitParameter(node); } readonly Comparison<T> func; public ExpressionComparer(Expression<Func<T, K>> expression) { var paramA = expression.Parameters[0]; var paramB = Expression.Parameter(typeof(T)); var f2 = (Expression<Func<T, K>>)new ParameterReplaceVisitor(expression.Parameters[0], paramB).Visit(expression); var compExp = Expression.Lambda<Comparison<T>>(Expression.Call(expression.Body, typeof(K).GetMethod(nameof(IComparable<K>.CompareTo), new[] { typeof(K) }), f2.Body), paramA, paramB); this.func = compExp.Compile(); } public int Compare(T x, T y) => func(x, y); public override bool Equals(object obj) => obj is ExpressionComparer<K> c && this.func == c.func; public override int GetHashCode() => func.GetHashCode(); } class ReverseComparer : IComparer<T> { private static Comparer<T> orig = Comparer<T>.Default; public int Compare(T y, T x) => orig.Compare(x, y); public override bool Equals(object obj) => obj is ReverseComparer; public override int GetHashCode() => GetType().GetHashCode(); } public static IComparer<T> CreateExp<K>(Expression<Func<T, K>> expression) where K : IComparable<K> => new ExpressionComparer<K>(expression); public static IComparer<T> DefaultReverse => new ReverseComparer(); } public class ΔDebugView<T> { private IEnumerable<T> collection; public ΔDebugView(IEnumerable<T> collection) { this.collection = collection ?? throw new ArgumentNullException(nameof(collection)); }[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => collection.ToArray(); }[DebuggerStepThrough] public class ConsoleReader { const int BufSize = 1 << 12; private readonly byte[] buffer = new byte[BufSize]; private readonly Stream input; private readonly Encoding encoding; private int pos = 0; private int len = 0; public ConsoleReader(Stream input, Encoding encoding) { this.input = input; this.encoding = encoding; } public ConsoleReader(Stream input) : this(input, Console.InputEncoding) { } private void MoveNext() { if (++pos >= len) { len = input.Read(buffer, 0, buffer.Length); if (len == 0) { buffer[0] = 10; } pos = 0; } } public int Int { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { int res = 0; bool neg = false; while (buffer[pos] < 48) { neg = buffer[pos] == 45; MoveNext(); } do { res = checked(res * 10 + (buffer[pos] ^ 48)); MoveNext(); } while (48 <= buffer[pos]); return neg ? -res : res; } } public int Int0 => this.Int - 1; public long Long { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { long res = 0; bool neg = false; while (buffer[pos] < 48) { neg = buffer[pos] == 45; MoveNext(); } do { res = res * 10 + (buffer[pos] ^ 48); MoveNext(); } while (48 <= buffer[pos]); return neg ? -res : res; } } public long Long0 => this.Long - 1; public string String { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { var sb = new List<byte>(); while (buffer[pos] <= 32) MoveNext(); do { sb.Add(buffer[pos]); MoveNext(); } while (32 < buffer[pos]); return this.encoding.GetString(sb.ToArray()); } } public string Ascii { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { var sb = new StringBuilder(); while (buffer[pos] <= 32) MoveNext(); do { sb.Append((char)buffer[pos]); MoveNext(); } while (32 < buffer[pos]); return sb.ToString(); } } public string Line { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { var sb = new List<byte>(); while (buffer[pos] <= 32) MoveNext(); do { sb.Add(buffer[pos]); MoveNext(); } while (buffer[pos] != 10 && buffer[pos] != 13); return this.encoding.GetString(sb.ToArray()); } } public char Char { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { while (buffer[pos] <= 32) MoveNext(); char res = (char)buffer[pos]; MoveNext(); return res; } } public double Double => double.Parse(this.Ascii);[DebuggerStepThrough] public struct RepeatReader { ConsoleReader cr; int count; public RepeatReader(ConsoleReader cr, int count) { this.cr = cr; this.count = count; } public T[] Select<T>(Func<ConsoleReader, T> factory) { var arr = new T[count]; for (var i = 0; i < count; i++) arr[i] = factory(cr); return arr; } public T[] Select<T>(Func<ConsoleReader, int, T> factory) { var arr = new T[count]; for (var i = 0; i < count; i++) arr[i] = factory(cr, i); return arr; } public string[] Line { get { var arr = new string[count]; for (var i = 0; i < count; i++) arr[i] = cr.Line; return arr; } } public string[] String { get { var arr = new string[count]; for (var i = 0; i < count; i++) arr[i] = cr.String; return arr; } } public string[] Ascii { get { var arr = new string[count]; for (var i = 0; i < count; i++) arr[i] = cr.Ascii; return arr; } } public int[] Int { get { var arr = new int[count]; for (var i = 0; i < count; i++) arr[i] = cr.Int; return arr; } } public int[] Int0 { get { var arr = new int[count]; for (var i = 0; i < count; i++) arr[i] = cr.Int0; return arr; } } public long[] Long { get { var arr = new long[count]; for (var i = 0; i < count; i++) arr[i] = cr.Long; return arr; } } public long[] Long0 { get { var arr = new long[count]; for (var i = 0; i < count; i++) arr[i] = cr.Long0; return arr; } } public double[] Double { get { var arr = new double[count]; for (var i = 0; i < count; i++) arr[i] = cr.Double; return arr; } } public static implicit operator int[](RepeatReader rr) => rr.Int; public static implicit operator long[](RepeatReader rr) => rr.Long; public static implicit operator double[](RepeatReader rr) => rr.Double; public static implicit operator string[](RepeatReader rr) => rr.Ascii; } public RepeatReader Repeat(int count) => new RepeatReader(this, count);[DebuggerStepThrough] public struct SplitReader { ConsoleReader cr; public SplitReader(ConsoleReader cr) { this.cr = cr; } public string[] String { get { while (cr.buffer[cr.pos] <= 32) cr.MoveNext(); var list = new List<string>(); do { if (cr.buffer[cr.pos] < 32) cr.MoveNext(); else list.Add(cr.String); } while (cr.buffer[cr.pos] != 10 && cr.buffer[cr.pos] != 13); return list.ToArray(); } } public string[] Ascii { get { while (cr.buffer[cr.pos] <= 32) cr.MoveNext(); var list = new List<string>(); do { if (cr.buffer[cr.pos] < 32) cr.MoveNext(); else list.Add(cr.Ascii); } while (cr.buffer[cr.pos] != 10 && cr.buffer[cr.pos] != 13); return list.ToArray(); } } public int[] Int { get { while (cr.buffer[cr.pos] <= 32) cr.MoveNext(); var list = new List<int>(); do { if (cr.buffer[cr.pos] < 32) cr.MoveNext(); else list.Add(cr.Int); } while (cr.buffer[cr.pos] != 10 && cr.buffer[cr.pos] != 13); return list.ToArray(); } } public int[] Int0 { get { while (cr.buffer[cr.pos] <= 32) cr.MoveNext(); var list = new List<int>(); do { if (cr.buffer[cr.pos] < 32) cr.MoveNext(); else list.Add(cr.Int0); } while (cr.buffer[cr.pos] != 10 && cr.buffer[cr.pos] != 13); return list.ToArray(); } } public long[] Long { get { while (cr.buffer[cr.pos] <= 32) cr.MoveNext(); var list = new List<long>(); do { if (cr.buffer[cr.pos] < 32) cr.MoveNext(); else list.Add(cr.Long); } while (cr.buffer[cr.pos] != 10 && cr.buffer[cr.pos] != 13); return list.ToArray(); } } public long[] Long0 { get { while (cr.buffer[cr.pos] <= 32) cr.MoveNext(); var list = new List<long>(); do { if (cr.buffer[cr.pos] < 32) cr.MoveNext(); else list.Add(cr.Long0); } while (cr.buffer[cr.pos] != 10 && cr.buffer[cr.pos] != 13); return list.ToArray(); } } public double[] Double { get { while (cr.buffer[cr.pos] <= 32) cr.MoveNext(); var list = new List<double>(); do { if (cr.buffer[cr.pos] < 32) cr.MoveNext(); else list.Add(cr.Double); } while (cr.buffer[cr.pos] != 10 && cr.buffer[cr.pos] != 13); return list.ToArray(); } } public static implicit operator int[](SplitReader sr) => sr.Int; public static implicit operator long[](SplitReader sr) => sr.Long; public static implicit operator double[](SplitReader sr) => sr.Double; public static implicit operator string[](SplitReader sr) => sr.Ascii; } public SplitReader Split => new SplitReader(this); public static implicit operator int(ConsoleReader cr) => cr.Int; public static implicit operator long(ConsoleReader cr) => cr.Long; public static implicit operator double(ConsoleReader cr) => cr.Double; public static implicit operator string(ConsoleReader cr) => cr.Ascii; public void Deconstruct(out ConsoleReader o1, out ConsoleReader o2) => (o1, o2) = (this, this); public void Deconstruct(out ConsoleReader o1, out ConsoleReader o2, out ConsoleReader o3) => (o1, o2, o3) = (this, this, this); public void Deconstruct(out ConsoleReader o1, out ConsoleReader o2, out ConsoleReader o3, out ConsoleReader o4) => (o1, o2, o3, o4) = (this, this, this, this); public void Deconstruct(out ConsoleReader o1, out ConsoleReader o2, out ConsoleReader o3, out ConsoleReader o4, out ConsoleReader o5) => (o1, o2, o3, o4, o5) = (this, this, this, this, this); public void Deconstruct(out ConsoleReader o1, out ConsoleReader o2, out ConsoleReader o3, out ConsoleReader o4, out ConsoleReader o5, out ConsoleReader o6) => (o1, o2, o3, o4, o5, o6) = (this, this, this, this, this, this); public void Deconstruct(out ConsoleReader o1, out ConsoleReader o2, out ConsoleReader o3, out ConsoleReader o4, out ConsoleReader o5, out ConsoleReader o6, out ConsoleReader o7) => (o1, o2, o3, o4, o5, o6, o7) = (this, this, this, this, this, this, this); public void Deconstruct(out ConsoleReader o1, out ConsoleReader o2, out ConsoleReader o3, out ConsoleReader o4, out ConsoleReader o5, out ConsoleReader o6, out ConsoleReader o7, out ConsoleReader o8) => (o1, o2, o3, o4, o5, o6, o7, o8) = (this, this, this, this, this, this, this, this); }[DebuggerStepThrough] public class ConsoleWriter {[DebuggerBrowsable(DebuggerBrowsableState.Never)] public readonly StreamWriter sw; public ConsoleWriter(Stream output) : this(output, Console.OutputEncoding) { } public ConsoleWriter(Stream output, Encoding encoding) { sw = new StreamWriter(output, encoding); } public void Flush() => sw.Flush(); public ConsoleWriter WriteLine(ReadOnlySpan<char> obj) { sw.WriteLine(obj); return this; } public ConsoleWriter WriteLine<T>(T obj) { sw.WriteLine(obj.ToString()); return this; } public ConsoleWriter WriteLineJoin<T>(ReadOnlySpan<T> col) => WriteMany(' ', col); public ConsoleWriter WriteLineJoin<T>(IEnumerable<T> col) => WriteMany(' ', col); public ConsoleWriter WriteLines<T>(ReadOnlySpan<T> col) => WriteMany('\n', col); public ConsoleWriter WriteLines<T>(IEnumerable<T> col) => WriteMany('\n', col); public ConsoleWriter WriteLineGrid<T>(IEnumerable<IEnumerable<T>> cols) { var en = cols.GetEnumerator(); while (en.MoveNext()) WriteLineJoin(en.Current); return this; } private ConsoleWriter WriteMany<T>(char sep, ReadOnlySpan<T> col) { var en = col.GetEnumerator(); if (!en.MoveNext()) return this; sw.Write(en.Current.ToString()); while (en.MoveNext()) { sw.Write(sep); sw.Write(en.Current.ToString()); } sw.WriteLine(); return this; } private ConsoleWriter WriteMany<T>(char sep, IEnumerable<T> col) { var en = col.GetEnumerator(); if (!en.MoveNext()) return this; sw.Write(en.Current.ToString()); while (en.MoveNext()) { sw.Write(sep); sw.Write(en.Current.ToString()); } sw.WriteLine(); return this; } } }
public partial class Program {[System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] public ConsoleReader cr;[System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] public ConsoleWriter cw; public Program(ConsoleReader reader, ConsoleWriter writer) { this.cr = reader; this.cw = writer; System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; } static void Main() => new Program(new ConsoleReader(Console.OpenStandardInput()), new ConsoleWriter(Console.OpenStandardOutput())).Run(); public void Run() { var res = Calc(); if (res is double) cw.WriteLine(Result((double)res)); else if (res is bool) cw.WriteLine(Result((bool)res)); else if (res != null) cw.WriteLine(res.ToString()); cw.Flush(); } }
public partial class Program
{
    public static string Result(double d) => d.ToString("0.####################", System.Globalization.CultureInfo.InvariantCulture);
    #endregion
    public static string Result(bool b) => b ? "Yes" : "No";
    private object Calc()
    {

        N = cr;
        SC = cr.Repeat(N).Select<(string, string, int)>(cr =>
        {
            string s = cr;
            int c = cr;
            return (s, new string(s.ToArray().Reverse()), c);
        });

        foreach (var (s,_,_) in SC)
        {
            if (s.Length == 20) throw new Exception();
        }


        foreach ((ReadOnlySpan<char> sp1, ReadOnlySpan<char> sp2, int c) in SC)
        {
            trieCx1.Add(sp1, c);
            trieCx2.Add(sp2, c);
            for (int i = 0; i < sp1.Length; i++)
            {
                var t1 = trieIx1.GetChild(sp1[i..], true);
                var t2 = trieIx2.GetChild(sp2[i..], true);

                if (!t1.HasValue) t1.Value = c1++;
                if (!t2.HasValue) t2.Value = c2++;
            }
        }

        trieIx1.Add("", c1 + c2 + 1);
        trieIx2.Add("", c2 + 1);

        var gb = new WGraphBuilder(c1 + c2 + 2, true);
        foreach ((ReadOnlySpan<char> sp1, ReadOnlySpan<char> sp2, int c) in SC)
        {
            gb.Add(c1 + c2, trieIx1.Get(sp1), c);

            for (int i = 0; i < sp1.Length; i++)
            {
                var ss1 = sp1[i..];
                var ss2 = sp2[i..];

                var tx1 = trieIx1.Get(ss1);
                var tx2 = c1 + trieIx2.Get(ss2);

                if (IsKaibun(ss1)) gb.Add(tx1, c1 + c2 + 1, 0);
                if (IsKaibun(ss2)) gb.Add(tx2, c1 + c2 + 1, 0);

                foreach (var (s, cc) in trieCx1.MatchGreedy(ss2))
                {
                    var tt = c1 + trieIx2.Get(ss2[s.Length..]);
                    gb.Add(tx2, tt, cc);
                }
                foreach (var (s, cc) in trieCx2.MatchGreedy(ss1))
                {
                    var tt = trieIx1.Get(ss1[s.Length..]);
                    gb.Add(tx1, tt, cc);
                }
                foreach (var (s, cc) in (trieCx1.GetChild(ss2)?.All() ?? Array.Empty<KeyValuePair<char[], int>>()))
                {
                    var tt = trieIx1.Get(s);
                    gb.Add(tx2, tt, cc);
                }
                foreach (var (s, cc) in (trieCx2.GetChild(ss1)?.All() ?? Array.Empty<KeyValuePair<char[], int>>()))
                {
                    var tt = c1 + trieIx2.Get(s);
                    gb.Add(tx1, tt, cc);
                }
            }
        }
        WNode[] graph = gb.ToArray();
#if DEBUG
        var ix1 = trieIx1.All().Select(p => KeyValuePair.Create(new string(p.Key), p.Value)).ToArray();
        var ix2 = trieIx2.All().Select(p => KeyValuePair.Create(new string(p.Key), p.Value)).ToArray();
#endif
        long res = graph.Dijkstra(c1 + c2)[^1];
        if (res >= 4611686018427387903) res = -1;
        return res;
    }
    bool IsKaibun(ReadOnlySpan<char> span)
    {
        for (int i = span.Length >> 1; i < span.Length; i++)
            if (span[i] != span[span.Length - 1 - i])
                return false;
        return true;
    }

    Trie<char, int> trieIx1 = new Trie<char, int>();
    Trie<char, int> trieIx2 = new Trie<char, int>();
    Trie<char, int> trieCx1 = new Trie<char, int>();
    Trie<char, int> trieCx2 = new Trie<char, int>();
    int N;
    (string s, string r, int c)[] SC;
    int c1, c2;
}
class WGraphBuilder { private List<Next>[] roots; private List<Next>[] children; public WGraphBuilder(int count, bool isOriented) { this.roots = new List<Next>[count]; this.children = new List<Next>[count]; for (var i = 0; i < count; i++) { if (isOriented) { this.roots[i] = new List<Next>(); this.children[i] = new List<Next>(); } else { this.roots[i] = this.children[i] = new List<Next>(); } } } public WGraphBuilder(int count, ConsoleReader cr, int edgeCount, bool isOriented) : this(count, isOriented) { for (var i = 0; i < edgeCount; i++) this.Add(cr.Int0, cr.Int0, cr.Int); } public void Add(int from, int to, int value) { children[from].Add(new Next { to = to, value = value }); roots[to].Add(new Next { to = from, value = value }); } public WNode[] ToArray() => Enumerable.Zip(roots, children, (root, child) => (root, child)).Select((t, i) => new WNode(i, t.root.ToArray(), t.child.ToArray())).ToArray(); public WTreeNode[] ToTree(int root) { if (this.roots[0] != this.children[0]) throw new Exception("木には無向グラフをしたほうが良い"); var res = new WTreeNode[this.children.Length]; res[root] = new WTreeNode(root, -1, 0, 0, this.children[root].ToArray()); var queue = new Queue<int>(); foreach (var child in res[root].children) { res[child.to] = new WTreeNode(child.to, root, 1, child.value, Array.Empty<Next>()); queue.Enqueue(child.to); } while (queue.Count > 0) { var from = queue.Dequeue(); if (res[from].root == -1) res[from].children = this.children[from].ToArray(); else { var children = new List<Next>(this.children[from].Count); foreach (var c in this.children[from]) if (c.to != res[from].root) children.Add(c); res[from].children = children.ToArray(); } foreach (var child in res[from].children) { res[child.to] = new WTreeNode(child.to, from, res[from].depth + 1, res[from].depthLength + child.value, Array.Empty<Next>()); queue.Enqueue(child.to); } } return res; } public WGraphBuilder Clone() { var count = this.roots.Length; var isOriented = this.roots[0] != this.children[0]; var cl = new WGraphBuilder(count, isOriented); for (int i = 0; i < count; i++) { if (isOriented) { cl.children[i] = this.children[i].ToList(); cl.roots[i] = this.roots[i].ToList(); } else cl.children[i] = cl.roots[i] = this.roots[i].ToList(); } return cl; } }
struct Next { public int to; public int value; public override string ToString() => $"to: {to} value:{value}"; }
class WTreeNode { public WTreeNode(int i, int root, int depth, long depthLength, Next[] children) { this.index = i; this.root = root; this.children = children; this.depth = depth; this.depthLength = depthLength; } public readonly int index; public readonly int root; public readonly int depth; public readonly long depthLength; public Next[] children; public override string ToString() => $"children: {string.Join(",", children)}"; public override bool Equals(object obj) { if (obj is WTreeNode) return this.Equals((WTreeNode)obj); else return false; } public bool Equals(WTreeNode other) => this.index == other.index; public override int GetHashCode() => this.index; }
class WNode { public WNode(int i, Next[] roots, Next[] children) { this.index = i; this.roots = roots; this.children = children; } public int index; public Next[] roots; public Next[] children; public override bool Equals(object obj) { if (obj is WNode) return this.Equals((WNode)obj); else return false; } public bool Equals(WNode other) => this.index == other.index; public override int GetHashCode() => this.index; public override string ToString() => $"children: ({string.Join("),(", children)})"; }

static class WGraphUtil
{
    [System.Diagnostics.DebuggerDisplay("Count = {" + nameof(Count) + "}")] class PriorityQueue<T> { protected readonly List<T> data; protected readonly IComparer<T> comparer; public PriorityQueue() : this(Comparer<T>.Default) { } public PriorityQueue(int capacity) : this(capacity, Comparer<T>.Default) { } public PriorityQueue(IComparer<T> comparer) { this.data = new List<T>(); this.comparer = comparer; } public PriorityQueue(int capacity, IComparer<T> comparer) { this.data = new List<T>(capacity); this.comparer = comparer; }[System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] public int Count => data.Count; public T Peek => data[0]; public void Add(T value) { data.Add(value); UpdateUp(data.Count - 1); } public T Dequeue() { var res = data[0]; data[0] = data[^1]; data.RemoveAt(data.Count - 1); UpdateDown(0); return res; } private void UpdateUp(int i) { if (i > 0) { var p = (i - 1) >> 1; if (comparer.Compare(data[i], data[p]) < 0) { (data[p], data[i]) = (data[i], data[p]); UpdateUp(p); } } } private void UpdateDown(int i) { var n = data.Count; var child = 2 * i + 1; if (child < n) { if (child != n - 1 && comparer.Compare(data[child], data[child + 1]) > 0) child++; if (comparer.Compare(data[i], data[child]) > 0) { (data[child], data[i]) = (data[i], data[child]); UpdateDown(child); } } }[System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.RootHidden)] private T[] Items => data.ToArray().Sort((a, b) => comparer.Compare(a, b)); }
    class PriorityQueue<TKey, TValue> : PriorityQueue<KeyValuePair<TKey, TValue>> { private class KeyComparer : IComparer<KeyValuePair<TKey, TValue>> { public readonly IComparer<TKey> comparer; public KeyComparer(IComparer<TKey> comparer) { this.comparer = comparer; } public int Compare(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y) => comparer.Compare(x.Key, y.Key); } public PriorityQueue() : this(Comparer<TKey>.Default) { } public PriorityQueue(int capacity) : this(capacity, Comparer<TKey>.Default) { } public PriorityQueue(IComparer<TKey> comparer) : base(new KeyComparer(comparer)) { } public PriorityQueue(int capacity, IComparer<TKey> comparer) : base(capacity, new KeyComparer(comparer)) { } public void Add(TKey key, TValue value) => Add(new KeyValuePair<TKey, TValue>(key, value)); }
    public static int MaxFlow(this WNode[] graph, int from, int to) { var capacities = new Dictionary<(int from, int to), int>(); for (int i = 0; i < graph.Length; i++) foreach (var next in graph[i].children) capacities.Add((i, next.to), next.value); var children = new HashSet<int>[graph.Length]; for (int i = 0; i < children.Length; i++) children[i] = new HashSet<int>(graph[i].children.Select(c => c.to)); var ret = 0; while (true) { var routes = new (int from, int to)[children.Length][]; var queue = new Queue<int>(children.Length); routes[from] = Array.Empty<ValueTuple<int, int>>(); queue.Enqueue(from); while (queue.Count > 0 && routes[to] == null) { var cur = queue.Dequeue(); foreach (var child in children[cur]) { var route = (cur, child); if (routes[child] == null && capacities[route] > 0) { routes[child] = new (int from, int to)[routes[cur].Length + 1]; routes[cur].CopyTo(routes[child], 0); routes[child][^1] = route; queue.Enqueue(child); } } } if (routes[to] == null) return ret; var min = int.MaxValue; foreach (var route in routes[to]) min = Math.Min(min, capacities[route]); ret += min; foreach (var route in routes[to]) { capacities[route] -= min; var rev = (route.to, route.from); children[route.to].Add(route.from); capacities.TryGetValue(rev, out int v); capacities[rev] = v + min; } } }
    public static long[][] WarshallFloyd(this WNode[] graph) { var res = NewArray(graph.Length, graph.Length, 0L); for (var i = 0; i < graph.Length; i++) { for (var j = 0; j < graph.Length; j++) { res[i][j] = long.MaxValue / 2; } res[i][i] = 0; foreach (var next in graph[i].children) res[i][next.to] = next.value; } for (var k = 0; k < graph.Length; k++) for (var i = 0; i < graph.Length; i++) for (var j = 0; j < graph.Length; j++) if (res[i][j] > res[i][k] + res[k][j]) res[i][j] = res[i][k] + res[k][j]; return res; }
    public static long[] Dijkstra(this WNode[] graph, int start) { var res = NewArray(graph.Length, long.MaxValue / 2); res[start] = 0; var used = new bool[graph.Length]; int count = 0; var remains = new PriorityQueue<long, int>(); remains.Add(0, start); while (remains.Count > 0) { var first = remains.Dequeue(); if (used[first.Value]) continue; used[first.Value] = true; if (++count >= graph.Length) break; foreach (var next in graph[first.Value].children) { var nextLength = first.Key + next.value; if (res[next.to] > nextLength) remains.Add(res[next.to] = nextLength, next.to); } } return res; }
    public static long[] BellmanFord(this WNode[] graph, int start) { var res = NewArray(graph.Length, long.MaxValue / 2); res[start] = 0; for (int i = 1; i <= graph.Length; i++) foreach (var node in graph) foreach (var next in node.children) if (res[next.to].UpdateMin(res[node.index] + next.value)) if (i == graph.Length) throw new InvalidOperationException("負の閉路"); return res; }
    public static WNode[] Prim(this WNode[] graph) { var sumi = new bool[graph.Length]; var pq = new PriorityQueue<int, (int from, int to)>(); var gb = new WGraphBuilder(graph.Length, false); sumi[0] = true; foreach (var next in graph[0].children) pq.Add(next.value, (0, next.to)); for (int i = 1; i < graph.Length; i++) { var t = pq.Dequeue(); if (sumi[t.Value.to]) { --i; continue; } sumi[t.Value.to] = true; gb.Add(t.Value.from, t.Value.to, t.Key); foreach (var next in graph[t.Value.to].children) if (!sumi[next.to]) pq.Add(next.value, (t.Value.to, next.to)); } return gb.ToArray(); }
}


class Trie<TKey, TValue>
{
    private readonly Dictionary<TKey, Trie<TKey, TValue>> children; public bool HasValue { private set; get; }
    private TValue _Value; public TValue Value { set { _Value = value; HasValue = true; } get => _Value; }
    public Trie() : this(EqualityComparer<TKey>.Default) { }
    public Trie(IEqualityComparer<TKey> comparer) { children = new Dictionary<TKey, Trie<TKey, TValue>>(comparer); }
    public Trie<TKey, TValue> Next(TKey key) => children.Get(key); public Trie<TKey, TValue> GetChild(ReadOnlySpan<TKey> key, bool force = false) { var trie = this; foreach (var k in key) { var child = trie.Next(k); if (child == null) { if (!force) return null; child = trie.children[k] = new Trie<TKey, TValue>(trie.children.Comparer); } trie = child; } return trie; }
    private bool GetAllChildren(ReadOnlySpan<TKey> key, out Stack<(TKey k, Trie<TKey, TValue> trie)> stack) { stack = new Stack<(TKey k, Trie<TKey, TValue>)>(); var trie = this; stack.Push((default, trie)); foreach (var k in key) { trie = trie.Next(k); if (trie == null) return false; stack.Push((k, trie)); } return true; }
    public void Add(ReadOnlySpan<TKey> key, TValue value) => GetChild(key, true).Value = value; public bool Remove(ReadOnlySpan<TKey> key) { if (!GetAllChildren(key, out var stack)) return false; var cur = stack.Pop(); if (!cur.trie.HasValue) return false; cur.trie.HasValue = false; while (stack.Count > 0 && !cur.trie.HasValue && cur.trie.children.Count == 0) { var (k, _) = cur; cur = stack.Pop(); cur.trie.children.Remove(k); } return true; }
    public TValue Get(ReadOnlySpan<TKey> key) { if (TryGet(key, out var val)) return val; throw new KeyNotFoundException(); }
    public bool TryGet(ReadOnlySpan<TKey> key, out TValue value) { var child = GetChild(key); if (child == null || !child.HasValue) { value = default; return false; } value = child.Value; return true; }
    private IEnumerable<KeyValuePair<TKey[], TValue>> All(List<TKey> list) { if (this.HasValue) yield return KeyValuePair.Create(list.ToArray(), this.Value); foreach (var (k, trie) in children) { list.Add(k); foreach (var p in trie.All(list)) yield return p; list.RemoveAt(list.Count - 1); } }
    public IEnumerable<KeyValuePair<TKey[], TValue>> All() => All(new List<TKey>());
    public MatchEnumerator MatchGreedy(ReadOnlySpan<TKey> key) => new MatchEnumerator(this, key); public ref struct MatchEnumerator
    {
        private Trie<TKey, TValue> trie; private readonly ReadOnlySpan<TKey> span; public MatchEnumerator Current => this; private int len; private TValue value;
        public MatchEnumerator(Trie<TKey, TValue> trie, ReadOnlySpan<TKey> span) { this.trie = trie; this.span = span; len = -1; value = default; }
        public bool MoveNext()
        {
            bool ok = false;
            while (trie != null && !ok)
            {
                if (trie.HasValue) { value = trie.Value; ok = true; }
                if (len + 1 < span.Length) trie = trie.Next(span[++len]);
                else { ++len; trie = null; }
            }
            return ok;
        }
        public MatchEnumerator GetEnumerator() => this; public void Deconstruct(out ReadOnlySpan<TKey> key, out TValue value) { key = span[..len]; value = this.value; }
    }
}
class Trie<T> : Trie<T, bool> { public Trie() : base() { } public Trie(IEqualityComparer<T> comparer) : base(comparer) { } public void Add(ReadOnlySpan<T> key) => Add(key, true); public bool Contains(ReadOnlySpan<T> key) => GetChild(key) != null; }