Pagini recente » Cod sursa (job #383449) | Cod sursa (job #1927587) | Cod sursa (job #768733) | Cod sursa (job #2461234) | Cod sursa (job #2715782)
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
ifstream cin ("matrice2.in");
ofstream cout ("matrice2.out");
struct idk {
int cost, x, y;
};
bool cmp(idk x, idk y) {
return x.cost > y.cost;
}
int n, q;
int tata[90005], ans[20005];
int a[305][305];
set <int> v[90005];
vector <idk> muchii;
inline int nr(int l, int c) {
return (l - 1) * n + c;
}
int find_daddy(int nod) {
int aux = nod;
while (tata[nod] > 0)
nod = tata[nod];
while (tata[aux] > 0) {
int aux2 = tata[aux];
tata[aux] = nod;
aux = aux2;
}
return nod;
}
void Union(int x, int y, int cost) {
x = find_daddy(x);
y = find_daddy(y);
if (tata[x] > tata[y])
swap(x, y);
tata[x] += tata[y];
tata[y] = x;
for (auto it = v[y].begin(); it != v[y].end(); ++it) {
auto it2 = v[x].find(*it);
if (it2 == v[x].end())
v[x].insert(*it);
else {
ans[*it] = cost;
v[x].erase(*it);
}
}
}
int main() {
cin >> n >> q;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
cin >> a[i][j];
tata[nr(i, j)] = -1;
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
if (j > 1) {
muchii.push_back({min(a[i][j], a[i][j - 1]), nr(i, j), nr(i, j - 1)});
}
if (i > 1) {
muchii.push_back({min(a[i][j], a[i - 1][j]), nr(i, j), nr(i - 1, j)});
}
}
}
sort (muchii.begin(), muchii.end(), cmp);
int x1, y1, x2, y2;
for (int i = 1; i <= q; ++i) {
cin >> x1 >> y1 >> x2 >> y2;
v[nr(x1, y1)].insert(i);
v[nr(x2, y2)].insert(i);
}
for (auto it : muchii) {
if (find_daddy(it.x) == find_daddy(it.y))
continue;
Union(it.x, it.y, it.cost);
}
for (int i = 1; i <= q; ++i)
cout << ans[i] << '\n';
return 0;
}