#include <stdio.h>
#include <stdlib.h>

const int NMAX=10000;
const unsigned int P8=256;

int n,p;

struct item {
  unsigned int D,M,G,C;
  unsigned int ind;
};

item tbl[NMAX];

void read_ip(unsigned int &ip){
  unsigned int a,b,c,d;
  scanf("%d.%d.%d.%d",&a,&b,&c,&d);
  ip = ((a*P8+b)*P8+c)*P8+d;
}

int sort_function(const void *_a, const void *_b)
{
  item *a = (item*) _a;  item *b = (item*) _b;
  if (a->M > b->M ) return -1;
  if (a->M < b->M ) return +1;
  if (a->C < b->C ) return -1;
  if (a->C > b->C ) return +1;
  if (a->ind > b->ind ) return -1;
  if (a->ind < b->ind ) return +1;
  return 0;
}

void print_ip (unsigned int ip) {
  unsigned int a,b,c,d;
  d = ip % 256; ip /=256;
  c = ip % 256; ip /=256;
  b = ip % 256; ip /=256;
  a = ip % 256; ip /=256;
  printf("%u.%u.%u.%u\n",a,b,c,d);
}

int main(void)
{
//  freopen("input.txt","r",stdin);
  //freopen("output.txt","w",stdout);

  scanf("%d",&n);
  for(int i=0; i<n; i++) {
    read_ip(tbl[i].D);
    read_ip(tbl[i].M);
    read_ip(tbl[i].G);
    scanf("%u",&tbl[i].C);
    tbl[i].D &= tbl[i].M; 
    tbl[i].ind = n-i;
  }

  //упорядочим по убыванию маски и ind
  qsort(tbl,n,sizeof(item),sort_function);

  scanf("%d",&p);
  for(int i=0; i<p; i++) {
    unsigned int A,j;
    read_ip(A);
    for(j=0; j<n; j++)
      if (tbl[j].D == (A & tbl[j].M) ) {
        print_ip(tbl[j].G);
        break;
      }
    if (j==n) printf("NO ROUTE\n");
  }

  return 0;
}