### subroutines

def formula
  dim0 = term()
  return nil if dim0.nil?

  while $fml[$pos] == '+' || $fml[$pos] == '-'
    $pos += 1
    dim1 = term()
    return nil if dim1.nil? || dim0 != dim1
  end
  dim0
end

def term
  dim0 = factor()
  return nil if dim0.nil?
  dim = dim0.clone

  while $fml[$pos] == '*' || $fml[$pos] == '/'
    op = $fml[$pos]
    $pos += 1

    dim1 = factor()
    return nil if dim1.nil?

    if op == '*'
      (0...dim0.length).each{|i| dim[i] += dim1[i]}
    else
      (0...dim0.length).each{|i| dim[i] -= dim1[i]}
    end
  end
  dim
end

def factor
  if $fml[$pos] == '('
    $pos += 1
    dim = formula()
    return nil if dim.nil? || $fml[$pos] != ')'
    $pos += 1
    return dim
  end

  dim = $fml[$pos]
  $pos += 1
  dim
end

### main

loop do
  n, m, pn = gets.split.map(&:to_i)
  break if (n | m | pn) == 0

  nm2dim = {}
  dim2nm = {}

  m.times do
    namei = gets.strip
    dsi = gets.split.map(&:to_i)
    nm2dim[namei] = dsi
    dim2nm[dsi] = namei
  end
  #p nm2dim
  #p dim2nm

  fstr = gets.strip

  vars = {}
  pn.times do
    vari, namei = gets.strip.split
    vars[vari] = namei
  end
  #p vars

  fs = fstr.split(/(\+|\-|\*|\/|\(|\)|[A-Za-z]+)/).select{|s| ! s.empty?}
  $fml = fs.map{|f| vars[f].nil? ? f : nm2dim[vars[f]]}
  #p fstr
  #p $fml

  $pos = 0

  dim = formula()

  if dim.nil?
    puts 'error'
  else
    nm = dim2nm[dim]
    puts (nm.nil? ? 'undefined' : nm)
  end
end