#include <bits/stdc++.h>
#define ff(i,a,b) for(int (i) = (a); (i) <= (b); ++(i))
#define pb push_back
using namespace std;
int dsu[105];
int sajz[105];
int n;
void init(int n){
    ff(i,1,n){
        dsu[i] = i;
        sajz[i] = 1;
    }
}
int findpar(int x){
    if(x == dsu[x])return x;
    return dsu[x] = findpar(dsu[x]);
}
void unite(int x, int y){
    int prvi = findpar(x);
    int drugi = findpar(y);
    if(sajz[prvi] > sajz[drugi]){
        dsu[prvi] = drugi;
        sajz[drugi] += sajz[prvi];
    }
    else{
        dsu[drugi] = prvi;
        sajz[prvi] += sajz[drugi];
    }
}
struct edge{
    int x,y;
    int duz;
};

int u[105][105],v[105][105],w[105][105];
vector<edge>grane;
bool cmp(edge a, edge b){
    return a.duz < b.duz;
}
int resi(int x1,int x2, int y1, int y2){
    init(n);
    grane.clear();
    ff(i,x1,x2){
        ff(j,y1,y2){
            grane.pb({u[i][j], v[i][j], w[i][j]});
        }
    }
    sort(grane.begin(), grane.end(), cmp);
    int res = 0;
    for(auto c:grane){
        int tren1,tren2;
        tren1 = c.x;
        tren2 = c.y;
        if(findpar(tren1) == findpar(tren2))continue;
        unite(tren1, tren2);
        res += c.duz;
    }
    ff(i,1,n){
        if(findpar(i) != findpar(1))return -1;
    }
    return res;

}
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++)
		O[i] = -1;
    n=N;
    ff(i,1,R){
        ff(j,1,C){
            u[i][j] = U[i][j];
            v[i][j] = V[i][j];
            w[i][j] = W[i][j];
        }
    }
    int q=Q;
    ff(i,1,q){
        int x1,y1,x2,y2;
        x1 = X1[i];
        x2 = X2[i];
        y1 = Y1[i];
        y2 = Y2[i];
        int pom = resi(x1,x2,y1,y2);
        O[i] = pom;
    }
}