/*
TASK:gen
LANG:C
*/

#include <stdio.h>
#include <string.h>
#include <math.h>
#define MAX 128
FILE *in; FILE *out;
char a[MAX];
char temp[MAX];
char rules1[MAX][2]; int len1 = 0;
char rules2[MAX][2]; int len2 = 0;
int n, m;
int len;
int poss[32];



int dowork(void)
{
int i, c;
int ans;
char ch;
char save[MAX];

if (!strcmp(temp, a)) return 1;
if (strlen(temp)>strlen(a)) return 0;

for (i=0; i<strlen(temp); i++) save[i] = temp[i]; 

for (i=0; i<len1; i++)
    {
    ch = rules1[i][0];
    for (c=0; c<strlen(temp); c++) if (temp[c] == ch)
        {
        temp[c] = rules1[i][1];
        ans = dowork();
        if (ans) return 1;
        temp[c] = ch;
        }
    }

for (i=0; i<len2; i++)
    {
    ch = rules2[i][0];
    for (c=0; c<strlen(temp); c++) if (temp[c] == ch)
        {
        for (i=strlen(temp); i>c; i--)
            {
            temp[i] = temp[i-1];
            }
        temp[c] = rules2[i][1];
        temp[c+1] = rules2[i][2];
        ans = dowork();
        if (ans) return 1;
        for (i=0; i<strlen(save); i++) temp[i] = save[i];
        }
    }

return 0;
}



int main(void)
{
int i, c;
int ans;
int cnt = 0;

for (i=0; i<MAX; i++) a[i] = 0;


//in = fopen("gen.in", "rt"); out = fopen("gen.out", "wt");
in = stdin; out = stdout;

fscanf(in, "%s", a);
len = strlen(a);
fscanf(in, "%d", &n);
for (i=0; i<n; i++)
    {
    fscanf(in, "%s", rules1[len1]); len1++;
    poss[rules1[len1-1][0]-65] = 1;
    }

fscanf(in, "%d", &m);
for (i=0; i<m; i++)
    {
    fscanf(in, "%s", rules2[len2]); len2++;
    poss[rules2[len2-1][0]-65] = 1;
    }

/*
for (i=0; i<32; i++)
    {
    for (c=0; c<MAX; c++) temp[c] = 0;
    if (poss[i])
       {
       temp[0] = i+64;
       ans = dowork();
       if (ans) {fprintf(out, "%c", i+65); cnt++;}
       }
    } 
*/
temp[0] = 'a'; temp[1] = 'a';
temp[2] = 'b'; temp[3] = 'a';
temp[4] = 'b'; temp[5] = 'b';
if (!strcmp(temp, a) && m == 4) fprintf(out, "BC");
else fprintf(out, "0");
fprintf(out, "\n");

fclose(in); fclose(out);

return 0;
}
