#include<bits/stdc++.h>
using namespace std;
#define int long long

int MOD=1000000007LL;
bool used[55][55][55][55];
int dp[55][55][55][55];

struct st{
  int n[4];
  st(){}
  st(int *a){
    for(int i=0;i<4;i++) n[i]=a[i];
  }
  st(int a0,int a1,int a2,int a3){
    n[0]=a0;n[1]=a1;n[2]=a2;n[3]=a3;
  }
};

signed main(){
  int n[4],m;
  for(int i=0;i<4;i++) cin>>n[i];
  cin>>m;
  cin.ignore();
  string s[m];
  for(int i=0;i<m;i++) getline(cin,s[i]);
  string key[m];
  vector<string> v[m];
  for(int i=0,j=0;i<m;i++,j=0){
    while(isalpha(s[i][j])) key[i]+=s[i][j++];
    j++;
    while(j<(int)s[i].size()){
      while(j<(int)s[i].size()&&s[i][j]==' ') j++;
      if(s[i][j]=='['){
	string t;
	j++;
	while(s[i][j]!=']') t+=s[i][j++];
	j++;
	v[i].push_back(t);
      }else{
	string t;
	while(j<(int)s[i].size()&&isalpha(s[i][j])) t+=s[i][j++];
	v[i].push_back(t);
      }
    }
  }
  map<string,int> ms;
  for(int i=0;i<m;i++) ms[key[i]]=i;
  
  int sum=0;
  for(int i=0;i<4;i++) sum+=n[i];
  //cout<<sum<<endl;
  
  int sz[m];
  
  for(int i=m-1;i>=0;i--){
    sz[i]=v[i].size();
    for(int j=0;j<(int)v[i].size();j++){
      if(islower(v[i][j][0])){
	int t=ms[v[i][j]];
	sz[i]+=sz[t]-1;
	if(sz[t]<=sum){
	  v[i].erase(v[i].begin()+j);
	  for(int k=0;k<sz[t];k++){
	    //cout<<v[t][k]<<endl;
	    v[i].insert(v[i].begin()+j+k,v[t][k]);
	  }
	}
      }
    }
    sz[i]=v[i].size();
  }

  /*//
  for(int i=0;i<m;i++){
    cout<<key[i]<<":";
    for(int j=0;j<sz[i];j++) cout<<" "<<v[i][j];
    cout<<endl;
  }
  //*/

  int ans=0;
  map<char,int> mc;
  mc['A']=0;
  mc['T']=1;
  mc['G']=2;
  mc['C']=3;
  
  for(int i=0;i<m;i++){
    //cout<<i<<"+"<<sz[i]<<endl;
    if(sz[i]!=sum) continue;
    memset(used,0,sizeof(used));
    memset(dp,0,sizeof(dp));
    queue<st> q;
    q.push(st(0,0,0,0));
    dp[0][0][0][0]=1;
    while(!q.empty()){
      st p=q.front();q.pop();
      int a[4],x=0;
      for(int j=0;j<4;j++) a[j]=p.n[j],x+=p.n[j];
      if(x==sum) break;
      //cout<<i<<"-"<<x<<":";
      //for(int j=0;j<4;j++) cout<<" "<<a[j];cout<<endl;
      for(int j=0;j<(int)v[i][x].size();j++){
	//cout<<j<<endl;
	int b[4];
	for(int k=0;k<4;k++) b[k]=a[k];
	if(b[mc[v[i][x][j]]]==n[mc[v[i][x][j]]]) continue;
	b[mc[v[i][x][j]]]++;
	(dp[b[0]][b[1]][b[2]][b[3]]+=dp[a[0]][a[1]][a[2]][a[3]])%=MOD;
	if(used[b[0]][b[1]][b[2]][b[3]]) continue;
	q.push(st(b));
	used[b[0]][b[1]][b[2]][b[3]]=1;
      }
    }
    (ans+=dp[n[0]][n[1]][n[2]][n[3]])%=MOD;
  }
  
  cout<<ans<<endl;
  return 0;
}