Cod sursa(job #2840059)

Utilizator mirceamaierean41Mircea Maierean mirceamaierean41 Data 27 ianuarie 2022 01:15:23
Problema Matrice 2 Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.43 kb
#include <fstream>
#include <vector>
#include <queue>
#include <vector>
#include <bitset>
using namespace std;

ifstream fin("matrice2.in");
ofstream fout("matrice2.out");

const int NMAX = 301;

int n, q, a[NMAX][NMAX], t[NMAX * NMAX], x1, y1, x2, y2;

int transform(int x, int y)
{
    return (x - 1) * n + y;
}

int dad(int x)
{
    if (t[x] == x)
        return x;
    return t[x] = dad(t[x]);
}

typedef pair<int, int> p;
typedef pair<p, p> pp;
typedef pair<pp, int> ppi;

vector<ppi> Q;
vector<int> s;

struct cmp
{
    inline bool operator()(const p &x, const p &y) const noexcept
    {
        return a[x.first][x.second] < a[y.first][y.second];
    }
};

priority_queue<p, vector<p>, cmp> pq;

int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};

bitset<NMAX> used[NMAX];

inline bool valid(int x, int y)
{
    return x && y && (x <= n) && (y <= n) && used[x][y] == 1;
}

void solve()
{
    while (!pq.empty())
    {
        int x = pq.top().first, y = pq.top().second;
        
        used[x][y] = 1;

        pq.pop();

        for (int i = 0; i < 4; ++i)
        {
            int nx = x + dx[i], ny = y + dy[i];
            if (valid(nx, ny))
            {
                int v1 = transform(x, y), v2 = transform(nx, ny);
                v1 = dad(v1);
                v2 = dad(v2);
                t[v2] = v1;
            }
        }

       /* for (int i = 0; i < q; ++i)
        {
            if (s[Q[i].second] == 0)
            {
                int v1 = transform(Q[i].first.first.first, Q[i].first.first.second), 
                    v2 = transform(Q[i].first.second.first, Q[i].first.second.second);
                
                v1 = dad(v1);
                v2 = dad(v2);
                if (v1 == v2)
                {
                    int ny = v1 % n;
                    if (ny == 0)
                        ny = n;
                    int nx = (v1 - ny) / n + 1;
                    s[Q[i].second] = a[nx][ny];
                }
            }
        }*/
    }
}

int main()
{
    fin >> n >> q;
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= n; ++j)
        {
            fin >> a[i][j];
            pq.push({i, j});
            int val = transform(i, j);
            t[val] = val;
        }

    for (int i = 0; i < q; ++i)
    {
        fin >> x1 >> y1 >> x2 >> y2;
        Q.push_back({{{x1, y1}, {x2, y2}}, i});
    }

    s.resize(q);

    solve();

    for (int i = 0; i < q; ++i)
        fout << s[i] << '\n';

    return 0;
}