#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct Grana
{
    int u;
    int v;
    int w;
};

bool cmp(Grana g1, Grana g2)
{
    return (g1.w<g2.w);
}

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)
	{
	    for(int i=1;i<=Q;i++)
        {
            int x1=X1[i], y1=Y1[i],x2=X2[i],y2=Y2[i];
            vector<Grana> grane;
            for(int j=x1;j<=x2;j++)
            {
                for(int k=y1;k<=y2;k++)
                {
                    Grana g;
                    g.u=U[j][k];
                    g.v=V[j][k];
                    g.w=W[j][k];
                    grane.push_back(g);
                }
            }
            sort(grane.begin(),grane.end(),cmp);
            long long mst=0;
            vector<int> koren(N+1);
            for(int j=1;j<=N;j++) koren[i]=-1;
            int brojac=0;
            for(int j=0;j<grane.size();j++)
            {
                Grana g;
                g=grane[j];
                int kor1=koren[g.u],kor2=koren[g.v];
                int cvor1=g.u,cvor2=g.v;
                //cout << cvor1 << " " << cvor2 << endl;
                while(kor1>0)
                {
                    cvor1=kor1;
                    kor1=koren[kor1];
                }
                while(kor2>0)
                {
                    cvor2=kor2;
                    kor2=koren[kor2];
                }
                if(cvor1!=cvor2)
                {
                    brojac++;
                    mst+=g.w;
                    if(kor1<kor2) koren[cvor2]=cvor1;
                    else cvor1=cvor2;
                    //cout << "* ";
                }
                if(brojac==N-1) break;
            }
            if(brojac!=N-1) O[i]=-1;
            else O[i]=mst;
        }
        return;
	}

static int** matrica(int R, int C) {
	int** a = new int*[R+1];
	for (int i=1; i<=R; i++)
		a[i] = new int[C+1];
	return a;
}

static void pocisti(int** a, int R) {
	for (int i=1; i<=R; i++)
		delete[] a[i];
	delete a;
}

int main() {
	ios_base::sync_with_stdio(false);
	//cin.tie(nullptr);

	int N, R, C, Q;
	cin >> N >> R >> C >> Q;

	int** U = matrica(R, C);
	int** V = matrica(R, C);
	int** W = matrica(R, C);

	int* X1 = new int[Q+1];
	int* Y1 = new int[Q+1];
	int* X2 = new int[Q+1];
	int* Y2 = new int[Q+1];
	int* O  = new int[Q+1];

	for (int i=1; i<=R; i++)
		for (int j=1; j<=C; j++)
			cin >> U[i][j] >> V[i][j] >> W[i][j];

	for (int i=1; i<=Q; i++)
		cin >> X1[i] >> Y1[i] >> X2[i] >> Y2[i];

	Resi(N, R, C, Q, U, V, W, X1, Y1, X2, Y2, O);

	for (int i=1; i<=Q; i++)
		cout << O[i] << '\n';

	delete[] X1;
	delete[] Y1;
	delete[] X2;
	delete[] Y2;
	delete[] O;

	pocisti(U, R);
	pocisti(V, R);
	pocisti(W, R);
}