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

#FW0000082. Đổi xâu theo đoạn chi phí nhỏ nhất II (Minimum Cost to Convert String II)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Đổi xâu theo đoạn chi phí nhỏ nhất II (Minimum Cost to Convert String II)

Minimum Cost to Convert String II

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

Given equal-length source and target strings, each rule converts one contiguous substring to another substring of equal length at a positive cost. Multiple conversions may be chained on the same segment, while distinct converted segments must not overlap. Unchanged characters cost zero. Minimize total cost.

Input

First s,ts,t, then mm lines of original replacement cost. Each rule maps strings of equal length.

Output

Print the minimum total cost or -1 if impossible.

Subtasks

  • Subtask 1 (40 points): 2≤∣s∣=∣t∣≤9, 1≤m≤102\le |s|=|t|\le9,\ 1\le m\le10. Chỉ dùng chữ thường a–z; hai chuỗi của mỗi quy tắc bằng độ dài, tối đa 55 ký tự trong bộ PHOJ; 1≤cost≤1091\le cost\le10^9.

  • Subtask 2 (60 points): 2≤∣s∣=∣t∣≤20, 1≤m≤222\le |s|=|t|\le20,\ 1\le m\le22. Chỉ dùng chữ thường a–z; hai chuỗi của mỗi quy tắc bằng độ dài, tối đa 55 ký tự trong bộ PHOJ; 1≤cost≤1091\le cost\le10^9.

Examples

Input

abcd
wxyz
4
ab wx 3
cd yz 2
a w 10
b x 10

Output

5

Explanation

Convert ab to wx for cost 3 and cd to yz for cost 2. These segments do not overlap, giving minimum total cost 5.