#include<bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define Rep(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
using namespace std;

const int n = 5;
string cur[5][5], nxt[5][5];
int a[50],b[50];

int main(){
  int t;
  int casenum = 1;

  while(cin >> t){
    if(t==0)break;
    if(casenum!=1)cout << endl;

    rep(i,5){
      rep(j,5)cin >> cur[i][j], nxt[i][j] = cur[i][j];
    }
    
    int m1,m2;
    cin >> m1;
    rep(i,m1)cin >> a[i];
    cin >> m2;
    rep(i,m2)cin >> b[i];

    while(t--){
      rep(i,n)rep(j,n)rep(k,n){
	int cnt = 0;
	Rep(ii,-1,2)Rep(jj,-1,2)Rep(kk,-1,2){
	  if(ii==0 && jj==0 && kk==0)continue;

	  int nx = i+ii, ny = j+jj, nz = k+kk;
	  if(nx<0 || ny<0 || nz<0)continue;
	  if(nx>=n || ny>=n || nz>=n)continue;
	  cnt += (cur[nx][ny][nz]=='1')?1:0;
	}
	bool f = false;
	if(cur[i][j][k] == '0'){
	  f = false;
	  rep(l,m1){
	    if(a[l] == cnt)f = true;
	  }
	}else{
	  rep(l,m2){
	    if(b[l] == cnt)f = true;
	  }
	}
	if(f)nxt[i][j][k] = '1';
	else nxt[i][j][k] = '0';
      }
    
      rep(i,n)rep(j,n)cur[i][j] = nxt[i][j];
    }

    cout << "Case " << casenum << ":" << endl;
    rep(i,n){
      rep(j,n)cout << cur[i][j] << endl;
      if(i+1!=n)cout << endl;
    }
    casenum++;
  }
}