/*一开始用数组做发现sort不能对他排序,改用结构体,学会了与运算*/
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
struct node
{
int a,b,c,d;
}ip[1001],sm[51],ans[1001];
int cmp(node x,node y)
{
if(x.a!=y.a) return x.a<y.a;
if(x.b!=y.b) return x.b<y.b;
if(x.c!=y.c) return x.c<y.c;
if(x.d!=y.d) return x.d<y.d;
}
int main()
{
int i,j;
int T,N,M,t;
scanf("%d",&T);
t=T;
while(T--)
{
memset(ip,0,sizeof(ip));
memset(sm,0,sizeof(sm));
memset(ans,0,sizeof(ans));
scanf("%d%d",&N,&M);
for(i=0;i<N;i++)
scanf("%d.%d.%d.%d",&ip[i].a,&ip[i].b,&ip[i].c,&ip[i].d);
for(i=0;i<M;i++)
scanf("%d.%d.%d.%d",&sm[i].a,&sm[i].b,&sm[i].c,&sm[i].d);
printf("Case #%d:\n",t-T);
for(i=0;i<M;i++)
{
int count=0;
for(j=0;j<N;j++)
{
ans[j].a=ip[j].a&sm[i].a;
ans[j].b=ip[j].b&sm[i].b;
ans[j].c=ip[j].c&sm[i].c;
ans[j].d=ip[j].d&sm[i].d;
}
sort(ans,ans+N,cmp);
for(j=0;j<N-1;j++)
{
if((ans[j].a==ans[j+1].a)&&(ans[j].b==ans[j+1].b)&&(ans[j].c==ans[j+1].c)&&(ans[j].d==ans[j+1].d))
count++;
}
printf("%d\n",N-count);
}
}
}