module Memoizable
	def memoize(name)
		original = "__original_#{name}__"
		([Class, Module].include?(self.class) ? self : self.class).class_eval {
			alias_method(original, name)
			private(original)
			cache = {}
			define_method(name){|*args|
				cache[args] ||= send(original, *args)
			}
		}
	end 
end
include Memoizable
na, nt, ng, nc = gets.split.map(&:to_i)
m = na + nt + ng + nc
n = gets.to_i
dna = gets.chomp.split[1..-1]
rule = {}
(n-1).times do
	name, *symbols = gets.chomp.split
	name.chop!
	rule[name] = symbols
end
until dna.all? {|v| v =~ /\[/}
	dna.map! {|v| rule[v] || v}
	dna.flatten!
	if dna.size > m
		puts 0
		exit
	end
end
if dna.size < m 
    puts 0
    exit
end
dna.map! { |v| v.split("")[1..-2] }
def f(dna, na, nt, ng, nc, i)
	return 0 if na < 0 || nt < 0 || ng < 0 || nc < 0
	return 1 if i == dna.size
	dna[i].map {|x| 
		case x
			when ?A; f(dna, na-1, nt, ng, nc, i+1)
			when ?T; f(dna, na, nt-1, ng, nc, i+1)
			when ?G; f(dna, na, nt, ng-1, nc, i+1)
			when ?C; f(dna, na, nt, ng, nc-1, i+1)
		end
	}.inject(:+) % 1_000_000_007
end
memoize :f
p f(dna, na, nt, ng, nc, 0)