Cod sursa(job #2736875)

Utilizator ZahaZaharie Stefan Zaha Data 4 aprilie 2021 09:06:16
Problema Matrice 2 Scor 35
Compilator cpp-64 Status done
Runda oni_wellcode_day_4 Marime 1.35 kb
#include <bits/stdc++.h>
using namespace std;

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

typedef tuple<int, int, int> triplePair;
auto cmp = [](triplePair left, triplePair right) {
    return get<0>(left) < get<0>(right);
};

const int N = 307;
int n, t;
int mx[N][N];
bitset<N> visited[N];
priority_queue<triplePair, vector<triplePair>, decltype(cmp)> q(cmp);

void add(int x, int y, int cost) {
    if (!visited[x][y])
        q.emplace(make_tuple(min(cost, mx[x][y]), x, y));
}

void solve() {
    while (!q.empty())
        q.pop();
    for (int i = 1; i <= n; ++i)
        visited[i].reset();

    int start_x, start_y, stop_x, stop_y;
    fin >> start_x >> start_y >> stop_x >> stop_y;

    q.emplace(make_tuple(mx[start_x][start_y], start_x, start_y));
    visited[start_x][start_y] = true;

    while (!q.empty()) {
        int cost = get<0>(q.top());
        int x = get<1>(q.top()), y = get<2>(q.top());
        q.pop();
        visited[x][y] = true;

        if (x == stop_x && y == stop_y) {
            fout << cost << "\n";
            return;
        }

        add(x - 1, y, cost);
        add(x, y - 1, cost);
        add(x + 1, y, cost);
        add(x, y + 1, cost);
    }
}

int main() {
    fin >> n >> t;
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= n; ++j)
            fin >> mx[i][j];

    while (t--)
        solve();
}