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

#FW0000080. Đồng nhất hai xâu (String Problem)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Đồng nhất hai xâu (String Problem)

String Problem

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

Given two equally long lowercase strings and directed, positively weighted character-conversion rules, convert both strings into the same target string at minimum total cost. Among optimal results output the lexicographically smallest target.

Input

First string ss, second string tt, then mm and mm directed rules a b cost using lowercase characters.

Output

Print -1 if impossible; otherwise the minimum total cost and the target string on separate lines.

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
bc
3
a b 3
b c 2
a c 10

Output

5
bc

Explanation

At position one, convert a into b for cost 3. At position two, convert b into c for cost 2. The common string bc costs 5.