
fun main(args:Array<String>):Unit {
    val (n, k) = readLine()!!.trim().split(' ').map(String::toInt)
    val mapper:MutableMap<Char, ReplaceMatrix> = mutableMapOf()
    repeat(k){
        val (p, h) = readLine()!!.trim().split(' ')
        val replace = Array(n){it}
        repeat(h.toInt() - 1){
            readLine()!!.trim().split(' ').map(String::toInt).forEachIndexed { index, i ->
                if (i == 1) {
                    val temp = replace[index]
                    replace[index] = replace[index + 1]
                    replace[index + 1] = temp
                }
            }
        }
        mapper[p.first()] = ReplaceMatrix(replace)
    }
    repeat(readLine()!!.trim().toInt()){
        val e = takeExpress(readLine()!!.trim(), mapper)!!
        println(e.first.toReplaceArray().map{it + 1}.joinToString(" "))
    }
}

class ReplaceMatrix(replace:Array<Int>) {
    private val mReplace:Array<Int> = replace
    operator fun times(that:ReplaceMatrix):ReplaceMatrix {
        return ReplaceMatrix(that.mReplace.map{mReplace[it]}.toTypedArray())
    }
    fun exp(e:Int):ReplaceMatrix {
        return when(e){
            0 -> ReplaceMatrix(Array(mReplace.size){it})
            1 -> this
            else -> exp(e / 2).let{
                if (e % 2 == 0) it * it
                else it * it * this
            }
        }
    }
    fun toReplaceArray():Array<Int> {
        return mReplace
    }
}
fun takeNumber(str:String):Pair<Int, String>? {
    return when{
        str.first().isDigit() -> {
            var i = 1
            while(i < str.length && str[i].isDigit()){
                ++i
            }
            Pair(str.substring(0, i).toInt(), str.substring(i))
        }
        else -> null
    }
}
fun takeToken(str:String, mapper:Map<Char, ReplaceMatrix>):Pair<ReplaceMatrix, String>? {
    return when{
        str.first().isUpperCase() -> Pair(mapper[str.first()]!!, str.substring(1))
        str.first() == '(' -> {
            val res = takeExpress(str.substring(1), mapper)!!
            Pair(res.first, res.second.substring(1))
        }
        else -> {
            val num = takeNumber(str)!!
            val res = takeToken(num.second, mapper)!!
            Pair(res.first.exp(num.first), res.second)
        }
    }
}
fun takeExpress(str:String, mapper:Map<Char, ReplaceMatrix>):Pair<ReplaceMatrix, String>? {
    return when{
        str.isEmpty() -> null
        else -> {
            val token = takeToken(str, mapper)!!
            if (token.second.isNotEmpty() && token.second.first() == '+') {
                val tail = takeExpress(token.second.substring(1), mapper)!!
                Pair(token.first * tail.first, tail.second)
            }else{
                token
            }
        }
    }
}
