/*
TASK:gen
LANG:C++
*/

#include <iostream>
#include <map>
#include <ctime>
#include <cstring>
#include <string>

using namespace std;

char s[ 128 ];
char nasl2[ 256 ][ 128 ][ 2 ];
char nasl1[ 256 ][ 128 ];
int nn1[ 256 ];
int nn2[ 256 ];
int seen[ 256 ];
map<string,bool> mm;
int n, m;
int t1;
int cnt=0;
bool ok1( const char *x )
{	int i, j;
	for ( i=0; i<strlen( x ); i++ )
	{	for ( j=1; j<=nn1[ x[ i ] ]; j++ )
			if ( nasl1[ x[ i ] ][ j ] == s[ i ] )
			 j = nn1[ x[ i ] ] + 7;
		if ( j < nn1[ x[ i ] ] + 7 )
		 return false;
	}
 return true;
}

bool ok( char x[ ] )
{
	if ( ( t1 - clock( ) ) / CLOCKS_PER_SEC > 0.1 )
		return false;
	if ( strlen( x ) > strlen( s ) )
		return false;
	if ( strlen( x ) == strlen( s ) && ok1( x ) )
		return true;
	char x1[ 128 ];
	if ( mm.count( x ) != 0 )
	return mm[ x ];
    bool res = false;
	int i, j, i1;
	for ( i=0; i<=strlen( x ); i++ )
	{	for ( j=1; j<=nn2[ x[ i ] ]; j++ )
		{
			for ( i1 = 0; i1 < i; i1++ )
				x1[ i1 ] = x[ i1 ];
			x1[ i1 ] = nasl2[ x[ i ] ][ j ][ 0 ];
			x1[ i1+1 ] = nasl2[ x[ i ] ][ j ][ 1 ];
			++i1; ++i1;
			for ( ; i1-1 < strlen( x ); i1++ )
				x1[ i1 ] = x[ i1-1 ];
			x1[ i1 ] = 0;
			res = res | ok( x1 );
			if ( res == true )
			{	string x2;
				x2.resize( strlen( x1 ) + 1 );
				x2 = x1;
				mm[ x1 ] = true;
				cnt++;
				return res;
			}
			else
			{
			 if ( cnt < 100000 )
			 {
				 mm[ x1 ] = false;
				 cnt++;
			 }
			}
		}
	}
	return res;
}

int main( )
{
	int i, j;
	char c, x, y;
	cin >> s;
	cin >> n;
	
	for ( c='A'; c<='Z'; c++ )
		nn1[ c ] = nn2[ c ] = 0;
	
	for ( i=1; i<=n; i++ )
	{ 	cin >> c;
		cin >> y;
		seen[ c ] = 7;
		nasl1[ c ][ ++nn1[ c ] ] = y;
	}
	cin >> m;
	for ( i=1; i<=m; i++ )
	{ 	cin >> c;
		cin >> x >> y;
		seen[ c ] = 7;
		nasl2[ c ][ ++nn2[ c ] ][ 0 ] = x;
		nasl2[ c ][ nn2[ c ] ][ 1 ] = y;
	}
	int f=0;
	for ( c='A'; c<='Z'; c++ )
	if ( seen[ c ]  == 7 )
	{ t1 = clock( );
		char w[ 128 ];
		w[ 0 ] = c;
		w[ 1 ] =0;
     if ( ok( w ) )
	  {  cout << c; f=1;}
	}
	if ( f==0 ) cout << 0;
	cout << endl;
	
	return 0;
}
