#include <bits/stdc++.h>

using namespace std;

vector< pair<int, pair<int, 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 j = 1; j <= R; j++) {
        for (int k = 1; k <= C; k++) {
            adj[U[j][k] - 1].push_back({V[j][k] - 1, {W[j][k], {j, k}}});
            adj[V[j][k] - 1].push_back({U[j][k] - 1, {W[j][k], {j, k}}});
        }
    }

    for (int i = 0; i < Q; i++){

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




        int minweight = 0;

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

        visited[firstnode] = true;


        for (int j = 0; j < adj[firstnode].size(); j++){
            if (adj[firstnode][j].second.second.first >= X1[i+1] && adj[firstnode][j].second.second.first <= X2[i+1] && adj[firstnode][j].second.second.second >= Y1[i+1] && adj[firstnode][j].second.second.second <= Y2[i+1])
                edges.push_back({adj[firstnode][j].first, adj[firstnode][j].second.first});
        }

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

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

            if (trgt == -1){
                break;
            }
            else {
                //cout << "dodajem node " << trgt << "\n";
                visited[trgt] = true;
                minweight += tmw;
                for (int k = 0; k < adj[trgt].size(); k++){
                    if (!visited[adj[trgt][k].first] && adj[trgt][k].second.second.first >= X1[i+1] && adj[trgt][k].second.second.first <= X2[i+1] && adj[trgt][k].second.second.second >= Y1[i+1] && adj[trgt][k].second.second.second <= Y2[i+1]){
                        edges.push_back({adj[trgt][k].first, adj[trgt][k].second.first});
                    }
                }
            }
        }

        for (int j = 0; j < N; j++){
            if(!visited[j]){
                //cout << j << " nije visited, abort mission\n";
                minweight = -1;
                break;
            }
        }


        O[i+1] = minweight;
    }

}