Pagini recente » Cod sursa (job #1558960) | Cod sursa (job #2742249) | Cod sursa (job #1750056) | Cod sursa (job #358086) | Cod sursa (job #1368233)
#include<bits/stdc++.h>
#define mp make_pair
#define PII pair<int,int>
#define fi first
#define se second
using namespace std;
struct cell
{
int val,x1,y1,x2,y2,oc;
};
struct celos
{
int val,x,y;
};
ifstream fin("matrice2.in");
ofstream fout("matrice2.out");
const int NMAX=505;
const int XMAX=20005;
int n,length,Q,a[NMAX][NMAX],sol[XMAX];
cell b[XMAX];
celos c[5*XMAX];
PII f[NMAX][NMAX];
int dx[]={ -1 , 0 , 1 , 0 };
int dy[]={ 0 , 1 , 0 , -1 };
inline void Union(int x,int y,int w,int z)
{
f[x][y].fi=w;
f[x][y].se=z;
}
inline PII Froid(PII aux)
{
PII kkt;
kkt.fi=f[aux.fi][aux.se].fi;
kkt.se=f[aux.fi][aux.se].se;
return kkt;
}
inline PII Father(int x,int y)
{
PII aux,w,z;
aux.fi=x;aux.se=y;
z=aux;
while (aux!=Froid(aux))
aux=Froid(aux);
while (z!=Froid(z))
{
w=Froid(z);
f[z.fi][z.se]=aux;
z=w;
}
return aux;
}
inline bool cmp(const celos A,const celos B)
{
return A.val>B.val;
}
inline bool cmp1(const cell A,const cell B)
{
return A.val>B.val;
}
int main()
{
int i,j,pw,ind;
PII aux,aux1;
fin>>n>>Q;
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
{
fin>>a[i][j];
length++;
c[length].val=a[i][j];
c[length].x=i;c[length].y=j;
}
sort(c+1,c+length+1,cmp);
for (i=1;i<=Q;i++)
{
fin>>b[i].x1>>b[i].y1>>b[i].x2>>b[i].y2;
b[i].val=0;b[i].oc=i;
}
for (pw=20;pw>=0;pw--)
{
//vedem daca la fiecare query b[i].val+(2^i)
//mentine pct in aceeasi componenta
//vectorul b[i] fiind sortat desc dupa val ca sa fac doar n^2 * log* n
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
{f[i][j].fi=i;f[i][j].se=j;}
ind=1;
for (i=1;i<=Q;i++)
{
while (ind<=length && c[ind].val>=(b[i].val+(1<<pw)))
{
for (j=0;j<4;j++)
if (a[c[ind].x+dx[j]][c[ind].y+dy[j]]>=c[ind].val)
{
aux=Father(c[ind].x,c[ind].y);
aux1=Father(c[ind].x+dx[j],c[ind].y+dy[j]);
if (aux!=aux1)
Union(aux.fi,aux.se,aux1.fi,aux1.se);
}
ind++;
}
aux=Father(b[i].x1,b[i].y1);
aux1=Father(b[i].x2,b[i].y2);
if (aux==aux1) b[i].val+=(1<<pw);
}
sort(b+1,b+Q+1,cmp1);
}
for (i=1;i<=Q;i++) sol[b[i].oc]=b[i].val;
for (i=1;i<=Q;i++) fout<<sol[i]<<"\n";
return 0;
}