Pagini recente » Cod sursa (job #2401951) | Cod sursa (job #2922085) | Cod sursa (job #931264) | Cod sursa (job #1177624) | Cod sursa (job #2630003)
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream cin("matrice2.in");
ofstream cout("matrice2.out");
const int NMAX = 300;
const int VALMAX = 1e6;
const int QMAX = 20000;
int N, Q;
int mat[NMAX + 2][NMAX + 2];
bool active[NMAX * NMAX + 2];
int dad[NMAX * NMAX + 2];
vector <int> qr[NMAX * NMAX + 2];
vector <pair <short int, short int>> posval[VALMAX + 2];
int ans[QMAX + 2];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
int Root(int node)
{
if(node == dad[node])
return node;
return dad[node] = Root(dad[node]);
}
void dojoin(int p, int q, int val)
{
p = Root(p);
q = Root(q);
if(p == q)
return;
dad[q] = p;
vector <int> n;
int pp = 0, qq = 0;
while(pp < (int)qr[p].size() && qq < (int)qr[q].size())
{
if(qr[p][pp] == qr[q][qq])
ans[qr[p][pp]] = val, pp++, qq++;
else if(qr[p][pp] < qr[q][qq])
n.push_back(qr[p][pp]), ++pp;
else
n.push_back(qr[q][qq]), ++qq;
}
while(pp < (int)qr[p].size())
n.push_back(qr[p][pp]), ++pp;
while(qq < (int)qr[q].size())
n.push_back(qr[q][qq]), ++qq;
qr[p] = n;
n.clear();
qr[q].clear();
}
void join(pair <int, int> p)
{
int x = p.first, y = p.second;
int pp = (x - 1) * N + y;
active[pp] = true;
for(int k = 0; k < 4; k++)
{
int xx = x + dx[k];
int yy = y + dy[k];
int pp2 = (xx - 1) * N + yy;
if(1 <= xx && xx <= N && 1 <= yy && yy <= N && active[pp2])
dojoin(pp, pp2, mat[x][y]);
}
}
int main()
{
cin >> N >> Q;
for(int i = 1; i <= N; i++)
for(int j = 1; j <= N; j++)
{
cin >> mat[i][j];
posval[mat[i][j]].push_back({i, j});
}
for(int i = 1; i <= Q; i++)
{
int x, y, xx, yy;
cin >> x >> y >> xx >> yy;
qr[(x - 1) * N + y].push_back(i);
qr[(xx - 1) * N + yy].push_back(i);
}
active[0] = false;
for(int i = 1; i <= N * N; i++)
{
dad[i] = i;
active[i] = false;
sort(qr[i].begin(), qr[i].end());
}
for(int i = 1000000; i >= 1; i--)
for(auto it : posval[i])
join(it);
for(int i = 1; i <= Q; i++)
cout << ans[i] << '\n';
return 0;
}