#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<set>
#include<vector>
using namespace std;
#define REP(i,b,n) for(int i=b;i<n;i++)
#define rep(i,n)   REP(i,0,n)
#define ALL(C)     (C).begin(),(C).end()

const int N = 255;
int order[N];
bool isleft[N];
void op(string &in,int &p,int cur,bool left,int maxlevel);

void exp(string &in,int &p,int cur,bool left,int maxlevel){
  int tmp=p;
  if (cur == 0){
    op(in,p,cur,left,maxlevel);
  }else {
    exp(in,p,cur-1,left,maxlevel);
  }
  while(p < in.size()){
    if (order[in[p]] != -1 && order[in[p]] == cur){
      p++;
      exp(in,p,cur,left,maxlevel);
      if (isleft[cur]== left){
	in.insert(in.begin()+tmp,'(');
	in.insert(in.begin()+p+1,')');
	p+=2;
      }
    }else {
      break;
    }
  }
}

void op(string &in,int &p,int cur,bool left,int maxlevel){
  if (in[p] == '('){
    p++;
    exp(in,p,maxlevel,left,maxlevel);
    p++;
  }else if (isalpha(in[p])){
    p++;
  }
}

void reverse(string &in){
  reverse(ALL(in));
  rep(i,in.size())
    if (in[i] == '(')in[i]=')';
    else if (in[i] == ')')in[i]='(';
}

void erase_bl(string &in){
  int n=in.size();
  int isneed[n];
  rep(i,in.size())isneed[i]=false;

  rep(i,in.size()){
    if (order[in[i]] != -1){
      int l=i-1,r=i+1;
      int cnt=0;
      while(l>=0){
	if (in[l]=='('){
	  cnt--;
	  if (cnt == -1 && !isneed[l]){
	    isneed[l]=i;
	    break;
	  }
	}else if (in[l] == ')')cnt++;
	l--;
      }
      cnt=0;//assert(cnt = 0)
      while(r<in.size()){
	if (in[r] == ')'){
	  cnt--;
	  if (cnt == -1 && !isneed[r]){
	    isneed[r]=i;
	    break;
	  }
	}else if (in[r] == '(')cnt++;
	r++;
      }
    }
  }


  //rep(i,in.size())cout << in[i]<<"  ";
  //rep(i,in.size())cout << isneed[i]<<" ";cout << endl;

  /*
  rep(i,in.size()){
    cout << i <<" " << in[i] <<" " << isneed[i] << endl;
  }
  */

  rep(i,in.size())
      if ((in[i]=='('||in[i]==')') &&isneed[i] == 0)
        in[i]=' ';

  in.erase(remove(in.begin(),in.end(),' '),in.end());
  //cout << "answer  "<<in << endl;
}

void solve(string &in,int level){
  int p=0;
  reverse(in);
  exp(in,p,level-1,true,level-1);

  //cout <<"mid "<< endl;
  p=0;
  reverse(in);
  //cout << "tar " << in << endl;
  exp(in,p,level-1,false,level-1);

  erase_bl(in);

  cout << in << endl;
}

int main(){
  int te;
  cin>>te;
  while(te--){
    rep(i,N)order[i]=-1;
    int m;
    cin>>m;
    rep(i,m){
      char lr;
      cin>>lr;
      if (lr == 'L'){
	isleft[m-i-1]=true;
      }else if (lr == 'R'){
	isleft[m-i-1]=false;
      }
      int num;
      cin>>num;
      rep(j,num){
	char tmp;
	cin>>tmp;
	order[tmp]=m-i-1;
      }
    }

    int q;
    cin>>q;
    rep(i,q){
      string in;
      cin>>in;
      solve(in,m);
    }
    if (te)cout << endl;
  }
  return false;
}