ns, ass, bss = ARGF.read.split("\n").map { |e| e.split }
n, m = ns.map { |e| e.to_i }
as = ass.map { |e| e.to_i }
bs = bss.map { |e| e.to_i }
xs = (1 ... n * m + 1).to_a.permutation.select { |e|
  flag = true
  amat = []
  bmat = []
  n.times { amat << [] }
  m.times { bmat << [] }
  e.each.with_index { |e, index|
    i = index / m
    j = index % m
    amat[i].push(e)
    bmat[j].push(e)
    if e > as[i] or e > bs[j]
      flag = false
      break
    end
  }
  if not flag
    flag
  else
    amat.each.with_index { |a, i|
      if a.max != as[i]
        flag = false
        break
      end
    }
    if not flag
      flag
    else
      bmat.each.with_index { |b, j|
        if b.max != bs[j]
          flag = false
          break
        end
      }
      flag
    end
  end
}

puts xs.length % (10 ** 9 + 7)