#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef unsigned long long ull;
const int N=1005,M=20050;
ull v[N];
inline ull getHash(char*s)
{
    ull ret=0;
    for(; *s; s++)
        ret=ret*131+*s;
    return ret;
}
int adj[N],nxt[M],to[M],ecnt;
inline void addEdge(int f,int t)
{
    ecnt++;
    nxt[ecnt]=adj[f];
    to[ecnt]=t;
    adj[f]=ecnt;
}
int dis[N];
void spfa(int s)
{
    static int que[N<<2];
    static bool inq[N];
    memset(inq,0,sizeof(inq));
    memset(dis,0x3f3f3f3f,sizeof(dis));
    int h,t;
    for(h=t=0,dis[s]=0,que[t++]=s; h^t; inq[h++]=false)
        for(int e=adj[que[h]]; e; e=nxt[e])
            if(dis[to[e]]>dis[que[h]]+1)
            {
                dis[to[e]]=dis[que[h]]+1;
                if(!inq[to[e]])
                    que[t++]=to[e],inq[to[e]]=true;
            }
}
int main()
{
    int n,m;
    while(scanf("%d",&n),n)
    {
        memset(adj,0,sizeof(adj));
        ecnt=0;
        char buf[12];
        for(int i=0; i<n; i++)
            scanf("%s",buf),v[i]=getHash(buf);
        sort(v,v+n);
        scanf("%d",&m);
        for(int i=0; i<m; i++)
        {
            scanf("%s",buf);
            int idx1=lower_bound(v,v+n,getHash(buf))-v;
            scanf("%s",buf);
            int idx2=lower_bound(v,v+n,getHash(buf))-v;
            addEdge(idx1,idx2),addEdge(idx2,idx1);
        }
        int ans=0;
        for(int i=0; i<n; i++)
        {
            spfa(i);
            for(int j=0; j<n; j++)
                if(i!=j&&dis[j]>ans)
                    ans=dis[j];
        }
        if(ans>0x20000000) ans=-1;
        printf("%d\n",ans);
    }
    return 0;
}
