Cod sursa(job #2480128)

Utilizator uvIanisUrsu Ianis Vlad uvIanis Data 24 octombrie 2019 22:25:47
Problema Matrice 2 Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.59 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, q, m[301][301];

bool viz[301][301];

bool ok(int x, int y)
{
    if(x > n || x < 1 || y > n || y < 1 || viz[x][y] == true) return false;
    return true;
}

struct comp{
    bool operator() (pair<int, int>& A, pair<int, int>& B)
    {
        return m[A.first][A.second] < m[B.first][B.second];
    }
};

priority_queue<pair<int, int>, vector<pair<int, int>>, comp> PQ;

int maxCost(int x1, int y1, int x2, int y2)
{
    int dx[] = {1, -1, 0, 0};
    int dy[] = {0, 0, 1, -1};

    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= n; ++j)
            viz[i][j] = false;



    PQ.push(make_pair(x1, y1));

    int ans = min(m[x1][y1], m[x2][y2]);

    while(!PQ.empty())
    {
        int x = PQ.top().first;
        int y = PQ.top().second;

        PQ.pop();

        ans = min(ans, m[x][y]);

        for(int k = 0; k < 4; ++k)
        {
            int newX = x + dx[k];
            int newY = y + dy[k];

            if(ok(newX, newY) == false) continue;

            if(newX == x2 && newY == y2) return ans;

            viz[newX][newY] = true;

            PQ.push(make_pair(newX, newY));
        }
    }

    return -1;
}

int main()
{
    fin >> n >> q;

    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= n; ++j)
            fin >> m[i][j];

    for(int i = 1; i <= q; ++i)
    {
        int x1, y1, x2, y2;
        fin >> x1 >> y1 >> x2 >> y2;

        fout << maxCost(x1, y1, x2, y2) << '\n';
    }
}