#include <bits/stdc++.h>
#define mid (l+r)/2
#define pb push_back
#define all(x) begin(x), end(x)
#define sz(x) int((x).size())
#define fi first
#define se second
#define pii pair<int,int>
#define lld long long
#define INF 1000000000
#define LINF 1000000000000000000LL
#define EPS 1e-9
#define PRINT(x) cerr<<#x<<"="<<x<<endl;
using namespace std;
#define MAXN 50
vector<pair<int,pii> > e;
int dsu[MAXN];
int root(int x) {
    while(x != dsu[x]) {
        dsu[x] = dsu[dsu[x]];
        x = dsu[x];
    }
    return x;
}
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] = 0;
        for(int x = X1[i]; x <= X2[i]; x++) {
            for(int y = Y1[i]; y <= Y2[i]; y++) {
                e.pb({W[x][y], {U[x][y], V[x][y]}});
            }
        }
        sort(all(e));
        for(int i = 1; i <= N; i++) dsu[i] = i;
        for(auto x : e) {
            int rtA = root(x.se.fi);
            int rtB = root(x.se.se);
            if(rtA != rtB) {
                dsu[rtA] = rtB;
                O[i] += x.fi;
            }
        }
        for(int i = 1; i <= N; i++) dsu[i] = root(i);
        int x = dsu[1];
        for(int i = 2; i <= N; i++) {
            if(dsu[i] != x) O[i] = -1;
        }
	}

}