#include <iostream>
#include <algorithm>
#include <vector>
#include <map>

using namespace std;
 
int n[2],m[2];
map< pair<string,string> , int > memo[501][501];
vector< vector<int> > a[2];
vector< vector<string> > b[2];
 
int dfs(int p1,int p2,string s1,string s2){
        if(p1 == n[0]-1 && p2 == n[1]-1) return (s1 == "" && s2 == "");
		if(memo[p1][p2].count(make_pair(s1,s2))) return memo[p1][p2][make_pair(s1,s2)];

        int ans = 0;
		if(p1 <= p2 || p2 == n[1]-1){
			for(int i = 0 ; i < a[0][p1].size() ; i++){
					string x = s1 + b[0][p1][i];
					string y = s2;
					int I = 0 , J = 0;
					for( ; I < x.size() && J < y.size() && x[I] == y[J] ; ) I++ , J++ ;
					if( I == x.size() || J == y.size() ){
							
							if( I == x.size() && I == y.size() ) x = "" , y = "";
							else if( I == x.size() ) x = "" , y = y.substr(J);
							else if( J == y.size() ) x = x.substr(I) , y = "";
							
							ans = ( ans + dfs(a[0][p1][i],p2,x,y) ) % 1000000007;
					}
			}
		}
        
		if(p1 > p2 || p1 == n[0]-1){
			for(int j = 0 ; j < a[1][p2].size() ; j++){
					string x = s1;
					string y = s2 + b[1][p2][j] ;
					int I = 0 , J = 0;
					for( ; I < x.size() && J < y.size() && x[I] == y[J] ; ) I++ , J++ ;
					if( I == x.size() || J == y.size() ){
							
							if( I == x.size() && I == y.size() ) x = "" , y = "";
							else if( I == x.size() ) x = "" , y = y.substr(J);
							else if( J == y.size() ) x = x.substr(I) , y = "";
							
							ans = ( ans + dfs(p1, a[1][p2][j],x,y) ) % 1000000007;
					}
			}
		}
        return memo[p1][p2][make_pair(s1,s2)] = ans;
}
 
int main(){
        int T;cin >> T;
        while(T--){
                for(int i = 0 ; i < 2 ; i++){
                        cin >> n[i] >> m[i];
                        //cout << n[i] << " " << m[i] << endl;
                        a[i].clear(); b[i].clear(); a[i].resize((unsigned)n[i]) , b[i].resize((unsigned)n[i]);
                        for(int j = 0 ; j < m[i] ; j++){
                                int A,B; string C;
                                cin >> A >> B >> C;
                                a[i][A].push_back(B);
                                b[i][A].push_back(C);
                        }
                }
				for(int i = 0 ; i < 501 ; i++)
					for(int j = 0 ; j < 501 ; j++)
						memo[i][j].clear();
                cout << dfs(0,0,"","") << endl;
        }
}