Pagini recente » Cod sursa (job #3158704) | Cod sursa (job #3283461)
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
//#include <bits/stdc++.h>
#define in fin
#define out fout
using namespace std;
ifstream fin("matrice2.in");
ofstream fout("matrice2.out");
const int ox[] = {0, 0, 1, -1};
const int oy[] = {1, -1, 0, 0};
struct cell{
int x, y, vl;
};
struct query{
int x1, y1, x2, y2, c1, c2, idx;
};
bool operator<(cell & a, cell & b){
return a.vl > b.vl;
}
bool operator>(query & a, query & b){
if(min(a.c1, a.c2) != min(b.c1, b.c2)) return min(a.c1, a.c2) > min(b.c1, b.c2);
else return max(a.c1, a.c2) > max(b.c1, b.c2);
}
int f[90001];
int s[90001];
int find_father(int & x){
if(x == f[x]) return x;
f[x] = find_father(f[x]);
return f[x];
}
bool in_acelasi_zet(int & a, int & b){
return (find_father(a) == find_father(b));
}
void add(int & a, int & b){
int f1 = find_father(a);
int f2 = find_father(b);
if(f1 == f2) return;
if(s[f1] > s[f2]){
s[f1] += s[f2];
f[f2] = f1;
}else{
s[f2] += s[f1];
f[f1] = f2;
}
}
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
for(int i = 0; i <= 90000; i++){
f[i] = i;
s[i] = 1;
}
int n, q; in >> n >> q;
int v[n][n];
cell l[n * n];
int vmax = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
in >> v[i][j];
l[i * n + j].vl = v[i][j];
l[i * n + j].x = i;
l[i * n + j].y = j;
vmax = max(vmax, i * n + j);
}
}
sort(l + 0, l + vmax + 1);
query qr[q];
for(int i = 0; i < q; i++){
in >> qr[i].x1 >> qr[i].y1 >> qr[i].x2 >> qr[i].y2;
qr[i].x1--; qr[i].y1--;
qr[i].x2--; qr[i].y2--;
qr[i].c1 = v[ qr[i].x1 ][ qr[i].y1 ];
qr[i].c2 = v[ qr[i].x2 ][ qr[i].y2 ];
qr[i].idx = i;
}
sort(qr + 0, qr + q, greater<query>());
int sol[q];
for(int i = 0; i < q; i++) sol[i] = 0;
int it = 0; // pt queries
for(int i = 0; i < n * n; i++){
// cout << "Adaugam " << l[i].vl << " ( " << l[i].x << " , " << l[i].y << " )\n";
int x = l[i].x, y = l[i].y;
for(int j = 0; j < 4; j++){
if(x + ox[j] < 0 || x + ox[j] >= n) continue;
if(y + oy[j] < 0 || y + oy[j] >= n) continue;
if(v[ x + ox[j] ][ y + oy[j] ] >= v[x][y]){
add( x * n + y, (x + ox[j]) * n + (y + oy[j]) );
}
}
int ii = it;
bool emptt = 0;
while(ii < q){
// cout << " -- > Inceram query : ( " << qr[ii].x1 << " , " << qr[ii].y1 << " ) cu ( " << qr[ii].x2 << " , " << qr[ii].y2 << " )\n";
if(qr[ii].c1 < v[x][y] || qr[ii].c2 < v[x][y]) break;
if(sol[qr[ii].idx] == 0 && in_acelasi_zet(qr[ii].x1 * n + qr[ii].y1, qr[ii].x2 * n + qr[ii].y2)) sol[ qr[ii].idx ] = v[x][y];
else if(sol[ qr[ii].idx ] == 0) emptt = 1;
ii++;
if(!emptt) it++;
}
}
for(int i = 0; i < q; i++) out << sol[i] << '\n';
return 0;
}