#include <bits/stdc++.h>
#define maxn 53
using namespace std;

int p[maxn], ans;
vector<pair<int, pair<int, int> > > es;

int findP(int x){
    if(x == p[x]){
        return p[x];
    }
    return p[x] = findP(p[x]);
}

bool join(int x, int y){
    x = findP(x);
    y = findP(y);
    if(x == y){
        return 0;
    }
    p[x] = y;
    return true;
}

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 i1 = 1; i1 <= Q; ++i1)
    {
        es.clear();
        for(int i = 1; i <= N; ++i){
            p[i] = i;
        }
        ans = 0;
        for(int i = X1[i1]; i <= X2[i1]; ++i){
            for(int j = Y1[i1]; j <= Y2[i1]; ++j){
                es.push_back({W[i][j], {U[i][j], V[i][j]}});
            }
        }
        sort(es.begin(), es.end());
        for(auto i : es){
            int u = i.second.first, v = i.second.second;
            // u -> v
            if(join(u, v)){
                ans += i.first;
            }
        }
        int minP = maxn, maxP = 0;
        for(int i = 1 ; i <= N; ++i){
            maxP = max(maxP, findP(i));
            minP = min(minP, findP(i));
        }
        if(maxP == minP){
            O[i1] = ans;
        } else {
            O[i1] = -1;
        }
    }
};