#include <bits/stdc++.h>
#define MP make_pair
#define F first
#define S second

using namespace std;

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)
{
	if (R <= 100 && C <= 100 && Q <= 100)
    {
        for (int k = 1; k <= Q; ++k)
        {
            bool vis[50];
            int s = 1;
            O[k] = 0;
            vector<pair<int, int>> a[50];
            for (int i = 0; i < 50; ++i) a[i].clear();
            priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
            while(!pq.empty()) pq.pop();
            for (int i = X1[k]; i <= X2[k]; ++i)
                for (int j = Y1[k]; j <= Y2[k]; ++j)
                {
                    //cout << U[i][j]-1 << " " << V[i][j]-1 << " " << W[i][j] << endl;
                    //cout.flush();
                    a[U[i][j]-1].push_back(MP(W[i][j], V[i][j]-1));
                    a[V[i][j]-1].push_back(MP(W[i][j], U[i][j]-1));
                }
            for (auto it : a[0])
                pq.push(it);
            for (int i = 1; i < N; ++i) vis[i] = false;
            vis[0] = true;
            while (!pq.empty())
            {
                auto t = pq.top();
                pq.pop();
                if (vis[t.S]) continue;
                //cout << t.F << " " << t.S << endl;
                vis[t.S] = true;
                s++;
                O[k] += t.F;
                for (auto it : a[t.S])
                    if (!vis[it.S])
                        pq.push(it);
            }
            if (s < N) O[k] = -1;
        }
    }
}