Pagini recente » Cod sursa (job #1270168) | Monitorul de evaluare | Cod sursa (job #2805344) | soldiers | Cod sursa (job #2783137)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("matrice2.in");
ofstream fout("matrice2.out");
const int MAXN = 3e2;
const int MAXV = 1e6;
const int MAXQ = 2e4;
const int di[] = {-1, 0, 1, 0}, dj[] = {0, 1, 0, -1};
int a[1 + MAXN][1 + MAXN], sol[1 + MAXQ];
pair<short, short> cells[1 + MAXN * MAXN + 1];
pair<int, int> q[1 + MAXQ];
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;
}
};
bool fcmp(const pair<short, short> &x, const pair<short, short> &y) {
return a[x.first][x.second] > a[y.first][y.second];
}
void test_case() {
int n, Q;
fin >> n >> Q;
auto id = [&](int i, int j) -> int {
return (i - 1) * n + j;
};
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
fin >> a[i][j];
cells[id(i, j)] = make_pair(i, j);
}
}
unordered_set<int> left;
for (int i = 1; i <= Q; ++i) {
int x1, y1, x2, y2;
fin >> x1 >> y1 >> x2 >> y2;
q[i] = make_pair(id(x1, y1), id(x2, y2));
left.emplace(i);
}
DSU tree(n * n);
auto inside = [&](int lin, int col) -> bool {
return 1 <= min(lin, col) && max(lin, col) <= n;
};
int N = n * n;
sort(cells + 1, cells + N + 1, fcmp);
for (int p = 1; p <= N; ++p) {
if (left.empty() == true) {
break;
}
int i, j;
tie(i, j) = cells[p];
int val = a[i][j];
bool ok = false;
while (p <= N) {
int curr_id = id(i, j);
for (int k = 0; k < 4; ++k) {
int iv = i + di[k], jv = j + dj[k];
if (inside(iv, jv) == true && a[iv][jv] >= val) {
if (tree.unite(curr_id, id(iv, jv))) {
ok = true;
}
}
}
tie(i, j) = cells[++p];
if (a[i][j] != val) {
break;
}
}
--p;
if (ok == true) {
vector<int> to_erase;
for (int i : left) {
if (tree.root(q[i].first) == tree.root(q[i].second)) {
sol[i] = val;
to_erase.emplace_back(i);
}
}
for (int it : to_erase) {
left.erase(it);
}
}
}
for (int i = 1; i <= Q; ++i) {
fout << sol[i] << '\n';
}
}
int main() {
int t = 1;
for (int tc = 1; tc <= t; ++tc) {
test_case();
}
fin.close();
fout.close();
return 0;
}