#include <algorithm>
#include <vector>

using namespace std;

int par[50], vel[50];

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

bool cmp(grana a, grana b)
{
    return a.w < b.w;
}

int parent(int x)
{
    while(par[x] != x)
        x = par[x];
    return x;
}

int unite(int a, int b)
{
    if(vel[a] < vel[b]) swap(a, b);
    par[b] = a;
    vel[a] += vel[b];
}

void resetDsu(int n)
{
    for(int i = 1; i <= n; i++)
        vel[i] = 1, par[i] = i;
}

grana mg(int u, int v, int w)
{
    grana g;
    g.u = u;
    g.v = v;
    g.w = w;
    return g;
}

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++)
	{

	    resetDsu(n);
        vector<grana> grane;
        for(int x = x1[i]; x <= x2[i]; x++)
        {
            for(int y = y1[i]; y <= y2[i]; y++)
            {
                grane.push_back(mg(u[x][y], v[x][y], w[x][y]));
            }
        }
        //cout << "Dodao" << endl;
        sort(grane.begin(), grane.end(), cmp);
        //cout << "Sort" << endl;
        int brKomp = n, tez = 0;
        for(grana gr : grane)
        {
            if(parent(gr.u) != parent(gr.v))
            {
                brKomp--;
                unite(gr.u, gr.v);
                tez += gr.w;
            }
        }
        if(brKomp == 1) o[i] = tez;
        else o[i] = -1;
	}

}