Pagini recente » Cod sursa (job #973602) | Cod sursa (job #1332155) | Cod sursa (job #2987197) | Cod sursa (job #973552) | Cod sursa (job #2784085)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("matrice2.in");
ofstream fout("matrice2.out");
const int NMAX(305), QMAX(20005);
map<int, int> mp;
vector<pair<int, int> > vec[NMAX * NMAX];
int cnt, cnvB[NMAX * NMAX], X1, Y1, X2, Y2, n, q, nrP, mat[NMAX][NMAX], aux[NMAX][NMAX], rez[QMAX];
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};
struct DSU {
vector<int> p, sz;
DSU(int n) {
p.resize(n + 1);
iota(p.begin(), p.end(), 0);
sz.assign(n + 1, 1);
}
int root(int x) {
if (x == p[x]) {
return x;
}
return p[x] = root(p[x]);
}
bool unite(int u, int v) {
int x = root(u), y = root(v);
if (x == y) {
return false;
}
if (sz[x] > sz[y]) {
swap(x, y);
}
p[x] = y;
sz[y] += sz[x];
return true;
}
};
int getId(int x, int y)
{
return (x - 1) * n + y;
}
int main()
{
fin >> n >> q;
set<int> s;
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j)
{
fin >> mat[i][j];
s.insert(mat[i][j]);
}
for(auto it: s)
{
mp[it] = ++cnt;
cnvB[cnt] = it;
}
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j)
{
mat[i][j] = mp[mat[i][j]];
vec[mat[i][j]].push_back({i, j});
}
vector<pair<int, int > > query;
query.push_back({0, 0});
for(int i = 1; i <= q; ++i)
{
fin >> X1 >> Y1 >> X2 >> Y2;
query.push_back({getId(X1, Y1), getId(X2, Y2)});
}
nrP = 0;
int step = 1;
for(; step < cnt; step <<= 1);
while(step)
{
vector<int> aq(q + 1, 0), parcg[cnt + 1];
for(int i = 1; i <= q; ++i)
if(rez[i] + step <= cnt)
{
aq[i] = rez[i] + step;
parcg[aq[i]].push_back(i);
}
DSU Arb(n * n);
++nrP;
for(int i = cnt; i >= 1; --i)
{
for(auto it: vec[i])
{
aux[it.first][it.second] = nrP;
for(int k = 0; k < 4; ++k)
{
int newX = it.first + dx[k];
int newY = it.second + dy[k];
if(aux[newX][newY] == nrP)
Arb.unite(getId(it.first, it.second), getId(newX, newY));
}
}
for(auto it: parcg[i])
if(Arb.root(query[it].first) == Arb.root(query[it].second))
rez[it] = aq[it];
}
step >>= 1;
}
for(int i = 1; i <= q; ++i)
fout << cnvB[rez[i]] << '\n';
return 0;
}