import std.stdio;
import std.c.stdio;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.regex;
import std.typecons;
 
void main() {
    int N;
    char F[5][5][5];
    int[] A, B;
    bool input() {
        scanf("%d\n", &N);
        if (N == 0) return false;
        foreach (z; 0 .. 5) {
            foreach (y; 0 .. 5) {
                foreach (x; 0 .. 5) {
                    scanf("%[01]", &F[z][y][x]);
                }
                scanf("%*[ \n]");
            }
        }
        int M;
        scanf("%d", &M);
        A = new int[M];
        foreach (i; 0 .. M) {
            scanf("%d", &A[i]);
        }
        scanf("%d", &M);
        B = new int[M];
        foreach (i; 0 .. M) {
            scanf("%d", &B[i]);
        }
        return true;
    }

    void step() {
        char nF[5][5][5];
        for (int z = 0; z < 5; z++) {
            for (int y = 0; y < 5; y++) {
                for (int x = 0; x < 5; x++) {
                    int C = 0;
                    for (int dz = -1; dz <= 1; dz++) {
                        for (int dy = -1; dy <= 1; dy++) {
                            for (int dx = -1; dx <= 1; dx++) {
                                if (dz == 0 && dy == 0 && dx == 0) continue;
                                if (0 <= z + dz && z + dz < 5 &&
                                    0 <= y + dy && y + dy < 5 &&
                                    0 <= x + dx && x + dx < 5 &&
                                    F[z + dz][y + dy][x + dx] == '1') {
                                    C++;
                                }
                            }
                        }
                    }
                    if ((F[z][y][x] == '0' ? A : B).count(C)) {
                        nF[z][y][x] = '1';
                    } else {
                        nF[z][y][x] = '0';
                    }
                }
            }
        }
        foreach (i; 0 .. 5) foreach (j; 0 .. 5) foreach (k; 0 .. 5)
            F[i][j][k] = nF[i][j][k];
    }

    void solve() {
        for (int i = 0; i < N; i++) {
            step;
        }
        foreach (i; 0 .. 5) {
            writeln(F[0][i]);
        }
        foreach (i; 1 .. 5) {
            writeln;
            foreach (j; 0 .. 5) {
                writeln(F[i][j]);
            }
        }
    }

    int T = 1;
    while (input) {
        if (T != 1) writeln;
        write("Case ", T, ":\n");
        solve;
        T++;
    }
}