#include <cstdio>
#include <cstdint>
#include <cassert>
#include <string>
#include <vector>
#include <algorithm>

std::string parse(std::string const& s, size_t& i,
                  std::vector<std::string> const& ops, size_t preced = 0) {

  if (preced == ops.size()) {
    if (s[i] == '(') {
      auto res = parse(s, ++i, ops, 0);
      assert(s[i] == ')');
      ++i;
      return res;
    }
    assert(isalpha(s[i]));
    return std::string(1, s[i++]);
  }

  auto res = parse(s, i, ops, preced+1);
  if (ops[preced][0] == 'L') {
    while (i < s.length()) {
      char op = s[i];
      if (!std::count(ops[preced].begin()+1, ops[preced].end(), op)) break;
      auto tmp = parse(s, ++i, ops, preced+1);
      res = "(" + res + op + tmp + ")";
    }
  } else {
    while (i < s.length()) {
      char op = s[i];
      if (!std::count(ops[preced].begin()+1, ops[preced].end(), op)) break;
      auto tmp = parse(s, ++i, ops, preced);
      res = "(" + res + op + tmp + ")";
    }
  }
  return res;
}

void solve_testcase() {
  size_t G;
  scanf("%zu", &G);

  std::vector<std::string> ops(G);
  for (size_t i = 0; i < G; ++i) {
    char A;
    size_t M;
    scanf(" %c %zu", &A, &M);
    ops[i] += A;
    for (size_t j = 0; j < M; ++j) {
      char op;
      scanf(" %c", &op);
      ops[i] += op;
    }
  }

  size_t N;
  scanf("%zu", &N);
  for (size_t i = 0; i < N; ++i) {
    char buf[128];
    scanf("%s", buf);
    std::string s = buf;
    size_t j = 0;
    printf("%s\n", parse(s, j, ops).c_str());
  }
}

int main() {
  int D;
  scanf("%d", &D);
  for (int i = 0; i < D; ++i) {
    if (i > 0) puts("");
    solve_testcase();
  }
}

