Cod sursa(job #2358187)

Utilizator papinub2Papa Valentin papinub2 Data 27 februarie 2019 22:10:22
Problema Matrice 2 Scor 35
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.64 kb
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

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

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

int drum (int x1, int y1, int x2, int y2, int n, vector<vector<int> >&v)
{
    queue<pair<int, int> > Q;
    vector<vector<int> > dp(n + 1, vector<int>(n + 1));

    dp[x1][y1] = v[x1][y1];
    Q.push(make_pair(x1, y1));

    while (!Q.empty())
    {
        pair<int, int> curent = Q.front();
        Q.pop();

        int curent_x = curent.first;
        int curent_y = curent.second;

        for (int i = 0; i <= 3; i++)
        {
            int new_x = curent_x + dx[i];
            int new_y = curent_y + dy[i];

            if (new_x >= 1 && new_x <= n && new_y >= 1 && new_y <= n)
                if (dp[new_x][new_y] == 0 || dp[new_x][new_y] < dp[curent_x][curent_y])
                {
                    int aux = dp[new_x][new_y];
                    dp[new_x][new_y] = min(v[new_x][new_y], dp[curent_x][curent_y]);

                    if (aux != dp[new_x][new_y])
                        Q.push(make_pair(new_x, new_y));
                }
        }
    }

    return dp[x2][y2];
}

int main()
{
    int n, T;

    in.sync_with_stdio(false);
    in >> n >> T;

    vector<vector<int> > v(n + 1, vector<int>(n + 1));

    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            in >> v[i][j];

    while(T--)
    {
        int x1, y1, x2, y2;
        in >> x1 >> y1 >> x2 >> y2;

        out << drum(x1, y1, x2, y2, n, v) << '\n';
    }

    return 0;
}