Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings. 

Input

The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.

Output

If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.

Examples

Input

uayd
uxxd
3
a x 8
x y 13
d c 3


Output

21
uxyd


Input

a
b
3
a b 2
a b 3
b a 5


Output

2
b


Input

abc
ab
6
a b 4
a b 7
b a 8
c b 11
c a 3
a c 0


Output

-1

Difficulty: MEDIUM_HARD
Tags: Shortest paths

Starter code:

Solutions:
import sys, string
import itertools
(s, t) = (input().strip(), input().strip())
if len(s) != len(t):
	print(-1)
	sys.exit()
vertices = string.ascii_lowercase
g = {c: {c: 0} for c in vertices}
n = int(input())
for i in range(n):
	(u, v, cost) = input().split()
	cost = int(cost)
	if v not in g[u] or g[u][v] > cost:
		g[u][v] = cost
for p in vertices:
	for u in vertices:
		if p not in g[u]:
			continue
		for v in vertices:
			if v not in g[p]:
				continue
			if v not in g[u] or g[u][v] > g[u][p] + g[p][v]:
				g[u][v] = g[u][p] + g[p][v]
best_costs = {c: {c: 0} for c in vertices}
best_chars = {c: {c: c} for c in vertices}
for (a, b) in itertools.product(vertices, vertices):
	if a == b:
		continue
	best_cost = None
	best_char = None
	for c in vertices:
		if c in g[a] and c in g[b]:
			if best_cost == None or best_cost > g[a][c] + g[b][c]:
				best_cost = g[a][c] + g[b][c]
				best_char = c
	if b in g[a] and (best_cost == None or best_cost > g[a][b]):
		best_cost = g[a][b]
		best_char = b
	if a in g[b] and (best_cost == None or best_cost > g[b][a]):
		best_cost = g[b][a]
		best_char = a
	if best_cost == None:
		continue
	best_costs[a][b] = best_cost
	best_chars[a][b] = best_char
total_cost = 0
chars = []
for (a, b) in zip(s, t):
	if b not in best_costs[a]:
		print(-1)
		sys.exit()
	total_cost += best_costs[a][b]
	chars.append(best_chars[a][b])
print(total_cost)
print(''.join(chars))


def calc_path(a):
	w = [[float('inf') for col in range(26)] for row in range(26)]
	for i in range(26):
		w[i][i] = 0
	for b in a:
		if w[ord(b[0]) - 97][ord(b[1]) - 97] > b[2]:
			w[ord(b[0]) - 97][ord(b[1]) - 97] = b[2]
	for k in range(26):
		for i in range(26):
			for j in range(26):
				if w[i][j] > w[i][k] + w[k][j]:
					w[i][j] = w[i][k] + w[k][j]
	return w

def test_calc_path():
	a = [['a', 'b', 2], ['a', 'c', 6], ['b', 'm', 5], ['c', 'm', 3]]
	m = calc_path(a)
	print(m)
	print(m[ord('a') - 97][ord('m') - 97])
	print(m[ord('a') - 97][ord('b') - 97])

def transfer(s, t, a):
	if len(s) != len(t):
		return -1
	r = ''
	z = 0
	w = calc_path(a)
	for (d, p) in zip(s, t):
		if d == p:
			r += d
		else:
			c = float('inf')
			q = ''
			i = ord(d) - 97
			j = ord(p) - 97
			for k in range(26):
				v = w[i][k] + w[j][k]
				if c > v:
					c = v
					q = chr(k + 97)
			if c == float('inf'):
				return -1
			z += c
			r += q
	r = str(z) + '\n' + r
	return r

def test_transfer():
	s = 'uayd'
	t = 'uxxd'
	a = [['a', 'x', 8], ['x', 'y', 13], ['d', 'c', 3]]
	assert transfer(s, t, a) == '21\nuxyd'
	s1 = 'a'
	t1 = 'b'
	a1 = [['a', 'b', 2], ['a', 'b', 3], ['b', 'a', 5]]
	assert transfer(s1, t1, a1) == '2\nb'
	s2 = 'abc'
	t2 = 'ab'
	a2 = [['a', 'b', 4], ['a', 'b', 7], ['b', 'a', 8], ['c', 'b', 11], ['c', 'a', 3], ['a', 'c', 0]]
	assert transfer(s2, t2, a2) == -1
	s3 = 'abcd'
	t3 = 'acer'
	a3 = [['b', 'c', 100], ['c', 'b', 10], ['c', 'x', 1], ['e', 'x', 3], ['c', 'e', 7], ['r', 'd', 11]]
	assert transfer(s3, t3, a3) == '25\nabxd'

def fun():
	s = input()
	t = input()
	n = int(input())
	a = []
	for c in range(n):
		(x, y, z) = map(str, input().split())
		a.append([x, y, int(z)])
	print(transfer(s, t, a))
fun()


s = input()
t = input()
if len(s) != len(t):
	print(-1)
	exit()
dist = [[10 ** 15 for j in range(26)] for i in range(26)]
for i in range(26):
	dist[i][i] = 0
n = int(input())
for i in range(n):
	a = input().split()
	x = ord(a[0]) - 97
	y = ord(a[1]) - 97
	w = int(a[-1])
	dist[x][y] = min(dist[x][y], w)
for k in range(26):
	for i in range(26):
		for j in range(26):
			dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
ans = ''
res = 0
n = len(s)
for i in range(n):
	if s[i] == t[i]:
		ans += s[i]
		continue
	cost = 10 ** 15
	pos = -1
	x = ord(s[i]) - 97
	y = ord(t[i]) - 97
	for j in range(26):
		if dist[x][j] + dist[y][j] < cost:
			cost = dist[x][j] + dist[y][j]
			pos = j
	if pos == -1:
		print(-1)
		exit()
	res += cost
	ans += chr(pos + 97)
print(res)
print(ans)


def code(c):
	return ord(c) - ord('a')

def main():
	a = input()
	b = input()
	m = int(input())
	n = 26
	d = [[10 ** 9 for i in range(n)] for j in range(n)]
	for i in range(n):
		d[i][i] = 0
	for i in range(m):
		(s, t, w) = input().split()
		w = int(w)
		s = code(s)
		t = code(t)
		d[s][t] = min(d[s][t], w)
	for k in range(n):
		for i in range(n):
			for j in range(n):
				d[i][j] = min(d[i][j], d[i][k] + d[k][j])
	if len(a) != len(b):
		print(-1)
	else:
		ans = 0
		res = []
		for i in range(len(a)):
			x = code(a[i])
			y = code(b[i])
			min_c = 'a'
			min_cost = 10 ** 9
			for j in range(n):
				cur = d[x][j] + d[y][j]
				if cur < min_cost:
					min_cost = cur
					min_c = chr(j + ord('a'))
			res.append(min_c)
			ans += min_cost
		if ans >= 10 ** 9:
			print(-1)
		else:
			print(ans)
			for j in res:
				print(j, end='')
			print()
main()


import sys
large = 10000000

def solve():
	s = input()
	t = input()
	if len(s) != len(t):
		print(-1)
		return
	n = int(input())
	mem = [[large] * 26 for _ in range(26)]
	for i in range(26):
		mem[i][i] = 0
	for i in range(n):
		(chra, chrb, strcost) = input().split()
		a = ord(chra) - ord('a')
		b = ord(chrb) - ord('a')
		cost = int(strcost)
		mem[a][b] = min(mem[a][b], cost)
		for start in range(26):
			for end in range(26):
				mem[start][end] = min(mem[start][end], mem[start][a] + mem[a][b] + mem[b][end])
	cost = 0
	res = [None] * len(s)
	for i in range(len(s)):
		mid = -1
		midcost = large
		a = ord(s[i]) - ord('a')
		b = ord(t[i]) - ord('a')
		for j in range(26):
			if mem[a][j] != -1 and mem[b][j] != -1:
				thiscost = mem[a][j] + mem[b][j]
				if thiscost < midcost:
					midcost = thiscost
					mid = j
		res[i] = chr(ord('a') + mid)
		cost += midcost
	if cost >= large:
		print(-1)
		return
	print(cost)
	print(''.join(map(str, res)))
if sys.hexversion == 50594544:
	sys.stdin = open('test.txt')
solve()


import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
ALPHA = 'abcdefghijklmnopqrstuvwxyz/'
M = 1000000007
EPS = 1e-06

def Ceil(a, b):
	return a // b + int(a % b > 0)

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
s = list(input())
t = list(input())
n = int(input())
dic = {}
adj = [[] for x in range(26)]
for x in range(n):
	(aa, bb, cost) = input().split(' ')
	cost = int(cost)
	a = ord(aa) - ord('a')
	b = ord(bb) - ord('a')
	chk = False
	for y in range(len(adj[a])):
		if adj[a][y][0] == b:
			adj[a][y][1] = min(cost, adj[a][y][1])
			chk = True
	if chk == False:
		adj[a].append([b, cost])
ans = []
vis = [False for x in range(26)]

def dfs(x, start, cnt):
	temp = chr(start + 97) + chr(x + 97)
	if temp in dic.keys() and cnt >= dic[temp]:
		return
	else:
		vis[x] = True
		temp = chr(start + 97) + chr(x + 97)
		if temp in dic.keys():
			dic[temp] = min(dic[temp], cnt)
		else:
			dic[temp] = cnt
		for z in adj[x]:
			dfs(z[0], start, cnt + z[1])
for x in range(26):
	adj[x].sort(key=lambda x: x[1])
for x in range(26):
	dfs(x, x, 0)
for x in range(ord('a'), ord('z') + 1):
	temp = chr(x) + chr(x)
	if temp in dic.keys():
		dic[temp] = 0
	else:
		dic[temp] = 0
chk = 1
spend = 0
if len(s) != len(t):
	print(-1)
else:
	for x in range(len(s)):
		if s[x] == t[x]:
			ans.append(s[x])
		else:
			notfound = True
			spendhere = int(1e+100)
			thechar = 'a'
			for y in range(ord('a'), ord('z') + 1):
				temp = s[x] + chr(y)
				retemp = t[x] + chr(y)
				if temp in dic.keys() and retemp in dic.keys():
					notfound = False
					if spendhere > dic[temp] + dic[retemp]:
						thechar = chr(y)
						spendhere = dic[temp] + dic[retemp]
			if notfound:
				chk = 0
				break
			else:
				ans.append(thechar)
				spend += spendhere
	if chk == 0:
		print(-1)
	else:
		print(spend)
		print(*ans, sep='')