Cod sursa(job #2836905)

Utilizator robertanechita1Roberta Nechita robertanechita1 Data 21 ianuarie 2022 09:30:07
Problema Matrice 2 Scor 35
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.66 kb
#include <bits/stdc++.h>

using namespace std;

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

int a[304][304], n, q;
int dx[] = {0,0,-1,1};
int dy[] = {-1,1,0,0};

struct elm
{
    int cost, x, y;
    bool operator < (const elm A) const
    {
        return cost < A.cost;
    }
};

void Bordare()
{
    for (int i = 0; i <= n + 1; i++)
        a[i][0] = a[0][i] = a[i][n+1] = a[n+1][i] = 2e9;
}

bool Vecin(int x1, int y1, int x2, int y2)
{
    if (abs (x1 -  x2) + abs(y1 - y2) == 1)
        return 1;
    return 0;
}

void Rezolvare(int x1, int y1, int x2, int y2)
{
    priority_queue< elm > q;
    bitset<305>viz[305];
    q.push({a[x1][y1], x1, y1});
    int costM = a[x1][y1];
    for (int i = 1; i <= n; i++)
        viz[i].reset();
    viz[x1][y1] = 1;
    while(q.top().x != x2 || q.top().y != y2)
    {
        int x = q.top().x;
        int y = q.top().y;
        costM = min(costM, a[x][y]);
        if(Vecin(x, y, x2, y2))
        {
            costM = min(costM, a[x2][y2]);
            break;
        }
        q.pop();
        for(int k = 0; k < 4; k++)
        {
            int i = x + dx[k];
            int j = y + dy[k];
            if(viz[i][j] == 0 && a[i][j] != 2e9)
                q.push({a[i][j], i, j});
            viz[i][j] = 1;
        }
    }
    fout << costM << "\n";
}

int main()
{
    fin >> n >> q;
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
            fin >> a[i][j];
    Bordare();
    for(int i = 1; i <= q; i++)
    {
        int x1, x2, y1, y2;
        fin >> x1 >> y1 >> x2 >> y2;
        Rezolvare(x1, y1, x2, y2);
    }
    return 0;
}