Pagini recente » Cod sursa (job #550549) | Cod sursa (job #588219) | Cod sursa (job #982118) | Cod sursa (job #327586) | Cod sursa (job #540345)
Cod sursa(job #540345)
#include<fstream>
#include<vector>
const int maxn = 302;
const int maxval = 1000005;
const int maxq = 25005;
using namespace std;
ifstream fin("matrice2.in");
ofstream fout("matrice2.out");
const int dx[5] = { 0 , 0 , 1 , -1 };
const int dy[5] = { 1 , - 1, 0 , 0 };
vector <pair <int , int > > list[maxval];
vector < int > list2[maxn * maxn];
vector< pair <int , int > > query(25000) , poz(maxn * maxn);
int i , j , k , q , mat[maxn][maxn] , dad[maxn * maxn] , lev[maxn * maxn] , sol[maxq] , aux[maxq] , v[maxn * maxn] , cnt , step;
int p[maxn * maxn] , p2[maxq];
int n , maxx , x , x2 ,y ,y2 , a;
int code (int i , int j) {
return n * (i - 1) + j;
}
int father( int nod ) {
int i , root = nod , aux;
for( ; root != dad[root] ; root = dad[root])
for( ; nod != root ; ) {
aux = nod;
nod = dad[nod];
dad[aux] = root;
}
return root;
}
void unite ( int A , int B ) {
if( lev [A] > lev[B] )
dad[B] = dad[A];
else
dad[A] = dad[B];
if( lev[A] == lev[B] )
lev[B]++;
}
void insert (int nr) {
int i;
int x = poz[nr].first;
int y = poz[nr].second;
for( i = 0 ; i <= 3 ; ++i ) {
int actx = x + dx[i];
int acty = y + dy[i];
if ( actx >= 1 && actx <= n && acty >= 1 && acty <= n ) {
if ( v[mat[actx][acty]] >= v[nr] )
unite (father(nr) , father(mat[actx][acty]));
}
}
}
bool cmp (int i , int j) {
return v[i] > v[j];
}
bool cmp2 (int i , int j) {
return aux[i] > aux[j];
}
bool same ( int A , int B ) {
return father(A) == father(B);
}
int main()
{
fin >> n >> q;
for( i = 1 ; i <= n ; ++i )
for( j = 1 ; j <= n ; ++j ) {
fin >> a , ++cnt;
poz[cnt].first = i , poz[cnt].second = j;
v[cnt] = a;
mat[i][j] = cnt;
}
for( i = 1 ; i <= cnt ; ++i )
p[i] = i;
for( i = 1 ; i <= q ; ++i )
p2[i] = i;
for( i = 1 ; i <= q ; ++i ) {
fin >> x >> y >> x2 >> y2;
query[i].first = mat[x][y];
query[i].second = mat[x2][y2];
}
sort( p + 1 , p + cnt + 1 , cmp);
for( step = 1 ; step <= v[p[1]] ; step <<= 1);
step >>= 1;
for ( ; step ; step >>= 1 ) {
for( i = 1 ; i <= q ; ++i ) aux[i] = sol[i] + step;
for( i = 1 ; i <= cnt ; ++i ) dad[i] = i , lev[i] = 1;
sort(p2 + 1 , p2 + q + 1 , cmp2);
int ind = 1;
for( i = 1 ; i <= cnt ; ++i ) {
insert(p[i]);
if ( i == cnt || v[p[i]] != v[p[i + 1]] ) {
for ( ;v[p[i + 1]] <= aux[p2[ind]] && ind <= q ; ++ind )
if ( same ( query[p2[ind]].first , query[p2[ind]].second) )
sol[p2[ind]] += step;
}
}
}
for( i = 1; i <= q ; ++i )
fout << sol[i] + 1 << "\n";
return 0;
}