Cod sursa(job #2736970)

Utilizator CosminMorarMorar Cosmin Andrei CosminMorar Data 4 aprilie 2021 11:35:36
Problema Matrice 2 Scor 35
Compilator cpp-64 Status done
Runda oni_wellcode_day_4 Marime 1.25 kb
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ifstream fin("matrice2.in");
ofstream fout("matrice2.out");
const int NMAX = 305;
int di[] = {-1, 0, 1, 0};
int dj[] = {0, 1, 0, -1};
int n, q, mat[NMAX][NMAX];
bitset<NMAX> reached[NMAX];
priority_queue<pair<int, pair<int, int>>> pq;

bool inside(int i, int j) {
	return i > 0 && j > 0 && i <= n && j <= n;
}

int main() {
	fin >> n >> q;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++)
			fin >> mat[i][j];
		
	while (q--) {
		int ist, jst, isf, jsf;
		fin >> ist >> jst >> isf >> jsf;
		
		for (int i = 1; i <= n; i++)
			reached[i] = 0;
		pq.push(make_pair(mat[ist][jst], make_pair(ist, jst)));
		
		while (!pq.empty()) {
			int iact = pq.top().second.first;
			int jact = pq.top().second.second;
			int cost = pq.top().first;
			pq.pop();
			
			for (int h = 0; h < 4; h++) {
				int ni = iact + di[h];
				int nj = jact + dj[h];
				if (!inside(ni, nj))
					continue;
				if (reached[ni][nj])
					continue;
					
				reached[ni][nj] = true;
				int ncost = min(cost, mat[ni][nj]);
				
				if (ni == isf && nj == jsf) {
					fout << ncost << '\n';
					while (!pq.empty())
						pq.pop();
					break;
				}
				
				pq.push(make_pair(ncost, make_pair(ni, nj)));
			}
		}	
	}
	return 0;
}