atcoder#ABC261G. [ABC261G] Replace

[ABC261G] Replace

Score : 600600 points

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.

ab
cbca
3
a b
b ca
a efg
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.

a
aaaaa
2
a aa
a aaa
2

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

a
z
1
a abc
-1

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