#include<iostream>
#include<set>
using namespace std;

char map[101][7][7][7];

int main() {
	int N, M1, M2, a, b, c, C;
	set<int> A, B;
	for(int z=0; z<7; ++z) {
		for(int y=0; y<7; ++y) {
			for(int x=0; x<7; ++x) {
				for(int t=0; t<101; ++t) {
					map[t][z][y][x] = '0';
				}
			}
		}
	}
	C = 1;
	while(1) {
		cin >> N;
		if(!N) break;
		if(C>1) cout << endl;
		A.clear(); B.clear();
		for(int z=1; z<=5; ++z) {
			for(int y=1; y<=5; ++y) {
				for(int x=1; x<=5; ++x) {
					cin >> map[0][z][y][x];
				}
			}
		}
		cin >> M1;
		for(int i=0; i<M1; ++i) {
			cin >> a; A.insert(a);
		}
		cin >> M2;
		for(int i=0; i<M2; ++i) {
			cin >> b; B.insert(b);
		}
		
		for(int t=0; t<N; ++t) {
			for(int z=1; z<=5; ++z) {
				for(int y=1; y<=5; ++y) {
					for(int x=1; x<=5; ++x) {
						c = 0;
						for(int z1=-1; z1<=1; ++z1) {
							for(int y1=-1; y1<=1; ++y1) {
								for(int x1=-1; x1<=1; ++x1) {
									if(!x1&&!y1&&!z1) continue;
									if(map[t][z+z1][y+y1][x+x1]=='1') c++;
								}
							}
						}
						if(map[t][z][y][x]=='1') {
							map[t+1][z][y][x] = (B.find(c)==B.end()?'0':'1');
						}else {
							map[t+1][z][y][x] = (A.find(c)==A.end()?'0':'1');
						}
					}
				}
			}
		}
		
		cout << "Case " << C << ":" << endl;
		for(int z=1; z<=5; ++z) {
			for(int y=1; y<=5; ++y) {
				for(int x=1; x<=5; ++x) {
					cout << map[N][z][y][x];
				}
				cout << endl;
			}
			if(z!=5) cout << endl;
		}
		C++;
	}
	return 0;
}