#include <bits/stdc++.h>
#define MAX_R 250
#define INF 10000000
using namespace std;

int U[MAX_R][MAX_R], V[MAX_R][MAX_R];
int W[3][MAX_R][MAX_R];
int seg[4*MAX_R][4*MAX_R];
int R, C;
void build(int row, int idx, int v, int l, int r){
    //printf("bld(%d, %d, %d, %d, %d)\n", row, idx, v, l, r);
    if(l+1==r){
            for(int t=0; t<3; ++t)
        seg[t][idx][v]=W[t][row][l];
        return;
    }
    int mid=(l+r)/2;
    build(row, idx, 2*v+1, l, mid);
    build(row, idx, 2*v+2, mid, r);
    for(int t=0; t<3; ++t)
    seg[t][idx][v]=min(seg[t][idx][2*v+1], seg[t][idx][2*v+2]);
    return;
}

int query(int idx, int v, int l, int r, int ql, int qr, int t){
    //("qry(%d, %d, %d, %d, %d, %d)\n", idx, v, l, r, ql, qr, t);
    if(ql>=r || qr<=l)return INF;
    if(ql<=l && r<=qr)return seg[t][idx][v];
    int mid=(l+r)/2;
    int ret=min(query(idx, 2*v+1, l, mid, ql, qr, t), query(idx, 2*v+2, mid, r, ql, qr, t));
    ///printf("ret=%d\n", ret);
    return ret;
}

void maxbuild(int v, int u, int l){
    //printf("mxb(%d, %d, %d)\n", v, u, l);
    if(u+1==l){
        build(u, v, 0, 0, C);
        return;
    }
    int mid=(u+l)/2;
    maxbuild(2*v+1, u, mid);
    maxbuild(2*v+2, mid, l);
    for(int t=0; t<3; ++t)
    for(int i=0; i<4*C; ++i)
            seg[t][v][i]=min(seg[t][2*v+1][i], seg[t][2*v+2][i]);
    return;
}

int maxquery(int v, int u, int l, int qu, int ql, int qxl, int qxr, int t){
   // printf("mxq(%d, %d, %d, %d, %d)\n", v, u, l, qu, ql);
    if(qu>=l || ql<=u) return INF;
    if(qu<=u && l<=ql) return query(v, 0, 0, C, qxl, qxr, t);
    int mid=(u+l)/2;
    return min(maxquery(2*v+1, u, mid, qu, ql, qxl, qxr, t), maxquery(2*v+2, mid, l, qu, ql, qxl, qxr, t));
}


void Resi(int N, int r, int c, int Q, int** u, int** v, int** w,
	int* X1, int* Y1, int* X2, int* Y2, int* O)
{
    memset(seg, INF, sizeof(seg));
    memset(W, INF, sizeof(W));
    R=r;
    C=c;
	for(int i=0; i<R; ++i)
        for(int j=0; j<C; ++j){
            U[i][j]=u[i+1][j+1];
            V[i][j]=v[i+1][j+1];
            if(U[i][j]+V[i][j]==3)
                W[0][i][j]=w[i+1][j+1];
            if(U[i][j]+V[i][j]==4)
                W[1][i][j]=w[i+1][j+1];
            if(U[i][j]+V[i][j]==5)
                W[2][i][j]=w[i+1][j+1];
        }
        
    maxbuild(0, 0, R);
    //for(int i=0; i<15; ++i)printf("%d ", seg[2][i]);
   // printf("\n");
    X1=X1+1;
    X2=X2+1;
    Y1=Y1+1;
    Y2=Y2+1;
    O=O+1;
    for(int i=0; i<Q; ++i){
            //cout<<"nove"<<endl;
            int a[3];
        for(int t=0; t<3; ++t)a[t]=maxquery(0, 0, R, X1[i]-1, X2[i], Y1[i]-1, Y2[i], t);
        int m=min(a[0]+a[1], a[0]+a[2]);
        O[i]=min(m, a[1]+a[2]);
        if(O[i]>1000000)O[i]=-1;
    }
    return;
}