PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FW0000081. Đổi xâu chi phí nhỏ nhất I (Minimum Cost to Convert String I)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Đổi xâu chi phí nhỏ nhất I (Minimum Cost to Convert String I)

Minimum Cost to Convert String I

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

Given equal-length lowercase source and target strings and positive-cost single-character transformation rules, find the minimum total cost to convert source into target using zero or more intermediate transformations, or -1.

Input

Input has source string ss, target string tt, then mm and mm directed rules from to cost.

Output

Print the minimum conversion cost or -1.

Subtasks

  • Subtask 1 (40 points): 1≤∣s∣=∣t∣≤8, 1≤m≤151\le |s|=|t|\le8,\ 1\le m\le15. Chỉ dùng chữ thường a–z; 1≤w≤1091\le w\le10^9; mọi quy tắc có hướng.

  • Subtask 2 (60 points): 1≤∣s∣=∣t∣≤25, 1≤m≤401\le |s|=|t|\le25,\ 1\le m\le40. Chỉ dùng chữ thường a–z; 1≤w≤1091\le w\le10^9; mọi quy tắc có hướng.

Examples

Input

ab
cc
3
a b 3
b c 2
a c 10

Output

7

Explanation

Converting a to c through b costs 5; converting the second b to c costs 2. The total is 7.