program Check;

{$APPTYPE CONSOLE}

uses
  TestLib, SysUtils;

const
  maxlen=500;

var
  s, sa, res, src, srch, s1: string;
  i, n, l, c, p, j: integer;
  a: array ['a'..'j','a'..'j'] of char;

begin
  s:= trim(ouf.ReadString); sa:= trim(ans.ReadString);
  if (s<>'YES') and (s<>'NO') then quit(_PE,Format('YES/NO expected, but [%s] found',[s]));
  if s<>sa then quit(_WA,Format('[%s] expected, but [%s] found',[sa,s]));
  if sa='NO' then begin
    if not ouf.SeekEof then quit(_PE,'Extra characters in output');
    quit(_OK,Format('result = [%s]',[sa]));
  end;
  res:= trim(ouf.ReadString);
  if not ouf.SeekEof then quit(_PE,'Extra characters in output');

  l:= length(res);
  if l>maxlen then quit(_PE,Format('Answer is too long (%d) characters',[l]));

  n:= inf.ReadLongint; inf.NextLine;
  for i:=1 to l do
    if (not (res[i] in ['a'..'j','(',')'])) or ((res[i] in ['a'..'j']) and (ord(res[i])-ord('a')+1>n)) then
      quit(_PE,Format('Unexpected symbol [%s]',[res[i]]));

  src:= inf.ReadString;
  srch:= inf.ReadString;
  for i:=1 to n do begin
    s:= inf.ReadString;
    for j:=1 to n do
      a[chr(ord('a')+i-1),chr(ord('a')+j-1)]:= s[j];
  end;

  s1:= res;
  while pos('(',s1) <> 0 do delete(s1,pos('(',s1),1);
  while pos(')',s1) <> 0 do delete(s1,pos(')',s1),1);

  if s1<>src then quit(_PE,Format('Answer without brackets not equal to source string',[]));

  c:= 0;
  for i:=1 to l do
    if res[i]='(' then inc(c)
    else if res[i]=')' then begin
      dec(c);
      if c<0 then quit(_PE,Format('Incorrect brackets sequence, pos=%d',[i]));
    end;

  if c<>0 then quit(_PE,Format('Incorrect brackets sequence: too much opening brackets',[]));

  res:= '('+res+')';
  p:= pos(')',res);
  while p<>0 do begin
    i:= p;
    while (i>0) and (res[i]<>'(') do dec(i);
    s:= copy(res,i+1,p-i-1);
    if p-i=1 then
      delete(res,i,p-i+1)
    else if p-i=2 then begin
      delete(res,i,p-i+1);
      insert(s,res,i);
    end else if p-i=3 then begin
      delete(res,i,p-i+1);
      insert(a[s[1],s[2]],res,i);
    end else quit(_PE,Format('Ambigous multiplication: pos=%d, ans=[%s]',[s]));
    p:= pos(')',res);
  end;

  if length(res)<>1 then quit(_Fail,Format('Wrong string multiplication, [%s]',[res]));

  if res[1]<>srch[1] then quit(_WA,Format('[%s] expected, but [%s] found',[srch[1],res[1]]))
  else quit(_OK,'result = '+sa);
end.
