#abc261g. G - Replace

G - Replace

Score : 600600 points

问题描述

你将得到两个由小写英文字母组成的字符串 SSTT

高桥以字符串 SS 为初始状态。他可以按任意顺序执行 KK 种操作任意次。 第 ii 种操作如下:

支付 11 的费用。然后,如果当前字符串包含 字符 CiC_i,选择其出现的任意一个位置,并用 字符串 AiA_i 替换它。否则,不做任何操作。

请找出使字符串变为 TT 所需的最小总费用。如果无法实现这一目标,则输出 1-1

以上为通义千问 qwen-max 翻译,仅供参考。

Problem Statement

You are given two strings SS and TT consisting of lowercase English letters.

Takahashi starts with the string SS. He can perform KK kinds of operations any number of times in any order.
The ii-th operation is the following:

Pay a cost of 11. Then, if the current string contains the character CiC_i, choose one of its occurrences and replace it with the string AiA_i. Otherwise, do nothing.

Find the minimum total cost needed to make the string equal TT. If it is impossible to do so, print 1-1.

Constraints

  • 1ST501\leq |S|\leq |T|\leq 50
  • 1K501\leq K\leq 50
  • CiC_i is a, b,\ldots, or z.
  • 1Ai501\leq |A_i|\leq 50
  • SS, TT, and AiA_i are strings consisting of lowercase English letters.
  • CiAiC_i\neq A_i, regarding CiC_i as a string of length 11.
  • All pairs (Ci,Ai)(C_i,A_i) are distinct.

Input

Input is given from Standard Input in the following format:

SS

TT

KK

C1C_1 A1A_1

C2C_2 A2A_2

\vdots

CKC_K AKA_K

Output

Print the minimum total cost needed to make the string equal TT. If it is impossible to do so, print 1-1.

Sample Input 1

ab
cbca
3
a b
b ca
a efg

Sample Output 1

4

Starting with S=S=ab, Takahashi can make T=T=cbca in four operations as follows:

  • Replace the 11-st character a in ab with b (Operation of the 11-st kind). The string is now bb.
  • Replace the 22-nd character b in bb with ca (Operation of the 22-nd kind). The string is now bca.
  • Replace the 11-st character b in bca with ca (Operation of the 22-nd kind). The string is now caca.
  • Replace the 22-nd character a in caca with b (Operation of the 11-st kind). The string is now cbca.

Each operation incurs a cost of 11, for a total of 44, which is the minimum possible.

Sample Input 2

a
aaaaa
2
a aa
a aaa

Sample Output 2

2

Two operations a \to aaa \to aaaaa incur a cost of 22, which is the minimum possible.

Sample Input 3

a
z
1
a abc

Sample Output 3

-1

No sequence of operations makes T=T=z from S=S=a.

update @ 2024/3/10 11:05:00