//UVA753APlugForUNIX
#include<cstdio>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<iostream>
#include<queue>
using namespace std;
const int maxn = 400 + 5;
const int INF = 1000000000;
map<string, int> id;
int cnt;
int device[maxn], target[maxn];
bool d[maxn][maxn];
vector<string> V;
struct Edge {
int from, to, cap, flow;
Edge(int u, int v, int c, int f) : from(u), to(v), cap(c), flow(f) { }
};
struct EdmondsKarp {
int n, m;
vector<Edge> edges;
vector<int> G[maxn];
int a[maxn];
int p[maxn];
void initial(int n) {
for(int i = 0; i < n; i++) G[i].clear();
edges.clear();
}
void AddEdge(int from, int to, int cap) {
edges.push_back(Edge(from, to, cap, 0));
edges.push_back(Edge(to, from, 0, 0));
m = edges.size();
G[from].push_back(m - 2);
G[to].push_back(m - 1);
}
int Maxflow(int s, int t) {//要输出起点和终点
int flow = 0;
while(1) {
memset(a, 0, sizeof(a));
queue<int> Q;
Q.push(s);
a[s] = INF;
while(!Q.empty()) {
int x = Q.front(); Q.pop();
for(int i = 0; i < G[x].size(); i++) {
Edge& e = edges[G[x][i]];
if(!a[e.to] && e.cap > e.flow) {
p[e.to] = G[x][i];
a[e.to] = min(a[x], e.cap - e.flow);
Q.push(e.to);
}
}
if(a[t]) break;
}
if(!a[t]) break;
for(int u = t; u != s; u = edges[p[u]].from) {
edges[p[u]].flow += a[t];
edges[p[u] ^ 1].flow -= a[t];
}
flow += a[t];
}
return flow;
}
};
int Id(const string& s) {
if(id.count(s) != 0) return id[s];
id[s] = cnt++;
V.push_back(s);
return id[s];
}
int n, m, k;
int main() {
int T;
scanf("%d", &T);
while(T--) {
id.clear();
V.clear();
cnt = 0;
int n;
string s, s2;
scanf("%d", &n);
for(int i = 0; i < n; i++) {
cin >> s;
target[i] = Id(s);
}
scanf("%d", &m);
for(int i = 0; i < m; i++) {
cin >> s >> s2;
device[i] = Id(s2);//用接受的设备来代替设备本身!!!
}
scanf("%d", &k);
memset(d, 0, sizeof(d));
for(int i = 0; i < k; i++) {
cin >> s >> s2;
d[Id(s)][Id(s2)] = 1;
}
int vertices = V.size();
for(int k = 0; k < vertices; k++)
for(int i = 0; i < vertices; i++)
for(int j = 0; j < vertices; j++)
d[i][j] |= d[i][k] & d[k][j];//Floyd
EdmondsKarp q;
q.initial(vertices + 2);//给s和t留出位置
for(int i = 0; i < m; i++) q.AddEdge(vertices, device[i], 1);
for(int i = 0; i < n; i++) q.AddEdge(target[i], vertices + 1, 1);
for(int i = 0; i < vertices; i++)
for(int j = 0; j < vertices; j++) if(d[i][j]) q.AddEdge(i, j, INF);
int r = q.Maxflow(vertices, vertices + 1);
printf("%d\n", m - r);
if(T) printf("\n");
}
return 0;
}
/*
1
4
A
B
C
D
5
laptop B
phone C
pager B
clock B
comb X
3
B X
X A
X D
*/