/*
#include <stdio.h>
#include <string.h>
// 4685. 경로 구하기
int queue[1000] = {0};
int front = 0;
int rear = 0;
int queueEmpty() {
return front == rear;
}
int queueSize() {
return rear - front;
}
void enqueue(int value) {
queue[rear++] = value;
}
int dequeue() {
return queue[front++];
}
int hamming(char* code1, char* code2) {
int distance = 0;
for (int i = 0; i < strlen(code1); i++) {
distance += code1[i] != code2[i];
}
return distance;
}
int main() {
int n, k, a, b, codeID;
char codes[1001][31] = {0};
scanf("%d %d", &n, &k);
for (int i = 1; i <= n; i++) {
scanf("%s", codes[i]);
}
int nextCode[1001] = {0};
scanf("%d %d", &a, &b);
nextCode[b] = -1;
enqueue(b);
while (!queueEmpty()) {
codeID = dequeue();
for (int i = 1; i <= n; i++) {
if (nextCode[i] == 0 && hamming(codes[codeID], codes[i]) == 1) {
nextCode[i] = codeID;
if (i == a) {
front = rear;
break;
}
enqueue(i);
}
}
}
if (nextCode[a] == 0) {
printf("-1");
} else {
codeID = a;
while (codeID != b) {
printf("%d ", codeID);
codeID = nextCode[codeID];
}
printf("%d", b);
}
return 0;
}
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char codes[100001][31] = {0};
int stack[100000] = {0};
int queue[100000] = {0};
int stackSize = 0;
int queueFront = 0;
int queueRear = 0;
int stackEmpty() {
return stackSize == 0;
}
void stackPush(int value) {
stack[stackSize++] = value;
}
int stackPop() {
return stack[--stackSize];
}
int queueEmpty() {
return queueFront == queueRear;
}
int queueSize() {
return (queueRear + 100000 - queueFront) % 100000;
}
void queueClear() {
queueFront = queueRear;
}
void enqueue(int value) {
queue[queueRear] = value;
queueRear = (queueRear + 1) % 100000;
}
int dequeue() {
queueFront = (queueFront + 1) % 100000;
return queue[(queueFront + 99999) % 100000];
}
int hamming(char* code1, char* code2) {
int distance = 0;
for (int i = 0; i < strlen(code1); i++) {
distance += code1[i] != code2[i];
}
return distance;
}
int main() {
int n, k, m, codeID;
scanf("%d %d", &n, &k);
for (int i = 1; i <= n; i++) {
scanf("%s", codes[i]);
}
int* prevCode = (int*)malloc(sizeof(int) * (n + 1));
int* targeted = (int*)malloc(sizeof(int) * (n + 1));
for (int i = 1; i <= n; i++) {
prevCode[i] = 0;
targeted[i] = 0;
}
int targets[50] = {0};
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%d", &targets[i]);
targeted[targets[i]] = 1;
}
int remainingTargets = m;
enqueue(1);
while (!queueEmpty()) {
codeID = dequeue();
for (int i = 2; i <= n; i++) {
if (prevCode[i] == 0 && hamming(codes[i], codes[codeID]) == 1) {
prevCode[i] = codeID;
if (targeted[i]) {
targeted[i] = 0;
remainingTargets -= 1;
if (remainingTargets == 0) {
queueClear();
break;
}
}
enqueue(i);
}
}
}
for (int i = 0; i < m; i++) {
if (targeted[targets[i]]) {
printf("-1\n");
continue;
}
for (int j = targets[i]; j > 1; j = prevCode[j]) {
stackPush(j);
}
printf("1 ");
while (!stackEmpty()) {
printf("%d ", stackPop());
}
printf("\n");
}
free(prevCode);
free(targeted);
return 0;
}