#include<stdio.h>
#include<string.h>
#include <iostream>
#include <algorithm>
#include<string>//必须加这个
#include<cstdio>
#define N 11000
#define NN 1100
#define inf 999999999
#include<map>
#include<queue>
using namespace std;
map<string,int>ymap;//对于用这个
struct node {
int x,next;
}f[N*2];
int dis[NN],len,n,head[NN];
void Add(int a,int b) {
f[len].x=b;f[len].next=head[a];
head[a]=len++;
}
int spfa(int u) {
int visit[NN];
memset(visit,0,sizeof(visit));
int cur,i,max;
for(i=0;i<n;i++)
dis[i]=inf;
queue<int>q;
q.push(u);
dis[u]=0;
visit[u]=1;
while(!q.empty()) {
cur=q.front();
q.pop();
for(i=head[cur];i!=-1;i=f[i].next) {
u=f[i].x;
if(!visit[u]) {
q.push(u);
visit[u]=1;
dis[u]=dis[cur]+1;
}
}
}
max=-1;
for(i=0;i<n;i++)
if(dis[i]>max)
max=dis[i];
return max;
}
int main() {
int m,i,f1,f2,ans,cnt;
char s[20],s1[20];
while(scanf("%d",&n),n) {
ymap.clear();
for(i=0;i<n;i++) {
scanf("%s",s);
ymap[s]=i;
}
len=0;
scanf("%d",&m);
memset(head,-1,sizeof(head));
while(m--) {
scanf("%s%s",s,s1);
f1=ymap[s];
f2=ymap[s1];
Add(f1,f2);Add(f2,f1);
}
cnt=-1;
for(i=0;i<n;i++) {
ans=spfa(i);
cnt=cnt>ans?cnt:ans;
}
if(cnt>=inf)
printf("-1
");
else
printf("%d
",cnt);
}
return 0;
}