#include <bits/stdc++.h>
#define PB push_back
#define MP make_pair
#define REP(i,n) for (int i=0;i<(n);i++)
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define ALL(a) (a).begin(),(a).end()
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> P;
const int INF=1e9;
int cnt;
int ans[10][10];
int fld[10][10];
int X,Y;
int B[15],K[15],Bx[15],By[15],N;
vector<int> V[15];
bool pos(int x,int y){
      return 0<=x&&x<X&&0<=y&&y<Y;
}
bool ok(int x,int y,int w,int h,int n){
      REP(i,w)REP(j,h)if(!pos(x+i,y+j)||(fld[x+i][y+j]!=0&&fld[x+i][y+j]!=n)){
            //cout<<i<<" "<<j<<"no"<<endl;
            return false;
      }
      return true;
}
void rec(int n){
      if(n==N){
            REP(i,X)REP(j,Y)ans[i][j]=fld[i][j];
            cnt++;
            return;
      }
      int sx,sy;
      //cout<<n<<" "<<B[n]<<endl;
      //REP(i,Y)REP(j,X)printf("%d%c",fld[j][i],j==X-1?'\n':' ');
      REP(i,X)REP(j,Y)if(fld[i][j]==B[n]){sx=i;sy=j;};
      //cout<<sx<<" "<<sy<<endl;
      REP(i,V[n].size()){
            //cout<<V[n][i]<<endl;
            for(int x=sx-V[n][i]+1;x<=sx;x++){
                  for(int y=sy-K[n]/V[n][i]+1;y<=sy;y++){
                        if(ok(x,y,V[n][i],K[n]/V[n][i],B[n])){
                              REP(j,V[n][i])REP(k,K[n]/V[n][i])fld[x+j][y+k]=B[n];
                              rec(n+1);
                              REP(j,V[n][i])REP(k,K[n]/V[n][i]){
                                    if(x+j==Bx[n]&&y+k==By[n])continue;
                                    else fld[x+j][y+k]=0;
                              }
                        }
                  }
            }
      }
      return;
}
int main(){
      while(cin>>X>>Y>>N&&(X||Y||N)){
            REP(i,15)V[i].clear();
            cnt=0;
            REP(i,N){
                  cin>>B[i]>>K[i];
                  for(int j=1;j*j<=K[i];j++){
                        if(K[i]%j==0){
                              V[i].PB(j);
                              if(K[i]/j!=j)V[i].PB(K[i]/j);
                        }
                  }
            }
            REP(i,Y)REP(j,X){
                  cin>>fld[j][i];
                  if(fld[j][i]!=0){
                        REP(k,N)if(B[k]==fld[j][i]){
                              Bx[k]=j;By[k]=i;
                        }
                  }
            }
            rec(0);
            if(cnt==1){
                  REP(i,Y)REP(j,X)printf("%d%c",ans[j][i],j==X-1?'\n':' ');
            }else{
                  cout<<"NA"<<endl;
            }
      }
}