#include <bits/stdc++.h>

using namespace std;

vector< pair<int, int> > adj[40];
bool visited[40];
vector< pair<int, int> > edges;

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 = 0; i < Q; i++){

        for (int j = 0; j < N; j++){
            visited[j] = false;
            adj[j].clear();
        }
        edges.clear();


        for (int j = X1[i] - 1; j <= X2[i] - 1; j++) {
            for (int k = Y1[i] - 1; k <= Y2[i] - 1; k++) {
                adj[U[j][k] - 1].push_back({V[j][k] - 1, W[j][k]});
                adj[V[j][k] - 1].push_back({U[j][k] - 1, W[j][k]});
            }
        }

        int minweight = 0;

        int firstnode = U[Y1[i] - 1][X1[i] - 1];

        visited[firstnode] = true;


        for (int j = 0; j < adj[firstnode].size(); j++){
            edges.push_back(adj[firstnode][j]);
        }

        for (int j = 0; j < N-1; j++){
            int tmw = 100000;
            int trgt = -1;
            for (int k = 0; k < edges.size(); k++){

                if(tmw > edges[k].second){
                    tmw = edges[k].second;
                    trgt = edges[k].first;
                }
            }

            if (trgt == -1){
                break;
            }
            else {
                visited[trgt] = true;
                minweight += tmw;
                for (int j = 0; j < adj[trgt].size(); j++){
                    if (!visited[adj[trgt][j].first]){
                        edges.push_back(adj[trgt][j]);
                    }
                }
            }
        }

        for (int j = 0; j < N; j++){
            if(!visited[j]){
                minweight = -1;
                break;
            }
        }


        O[i] = -1;
    }

}