from typing import cast
class Solution:
def minimumCost(
self,
source: str,
target: str,
original: list[str],
changed: list[str],
cost: list[int],
) -> int:
BASE = ord('a')
def to_i(a: str) -> int:
return ord(a) - BASE
MAX = float('inf')
m = [[MAX for _ in range(26)] for _ in range(26)]
for s, t, c in zip(
map(to_i, original),
map(to_i, changed),
cost,
):
current_val = m[s][t]
m[s][t] = min(current_val, c)
for k in range(26):
for i in range(26):
for j in range(26):
another_path = m[i][k] + m[k][j]
m[i][j] = min(m[i][j], another_path)
result = 0
for s, t in zip(
map(to_i, source),
map(to_i, target),
):
is_same = s == t
distance = 0 if is_same else m[s][t]
if distance == MAX:
return -1
result += cast(int, distance)
return result