Pagini recente » Cod sursa (job #1446339) | Cod sursa (job #2862357) | Cod sursa (job #170285) | Cod sursa (job #842766) | Cod sursa (job #3206507)
#include <fstream>
#include <set>
#include <algorithm>
#include <vector>
using namespace std;
ifstream fin("matrice2.in");
ofstream fout("matrice2.out");
int n,qsz;
const int nmax = 300;
struct el
{
int val;
int x;
int y;
} v[nmax*nmax + 5];
int mi[nmax+5][nmax + 5];
int k;
struct query{
int x1;
int x2;
int y1;
int y2;
int ind;
bool operator <(const query& b) const
{
return ind<b.ind;
}
};
int t[nmax * nmax + 5];
set<query> qi[nmax* nmax + 5];
vector <int> op[nmax * nmax + 5];
int sol[20005];
int dx[]={1,-1,0,0};
int dy[]={0,0,-1,1};
int vl;
bool inmat(int x,int y)
{
return x>=1 && x<=n && y>=1 && y<=n;
}
int rad(int x)
{
int cp=x;
for(;t[x]>0;x=t[x]);
while(cp!=x)
{
int aux = t[cp];
t[cp]=x;
cp=aux;
}
return cp;
}
bool join(int x,int y)
{
int rx = rad(x);
int ry = rad(y);
if(rx==ry)
return false;
if(-t[rx]<-t[ry])
swap(rx,ry);
t[rx]+=t[ry];
for(auto& j : qi[ry])
if(qi[rx].find(j)!=qi[rx].end())
{
sol[j.ind] = vl;
qi[rx].erase(j);
}
else
qi[rx].insert(j);
t[ry]=rx;
return true;
}
int main()
{
fin>>n>>qsz;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
{
int x;
fin>>x;
v[++k]= {x,i,j};
}
sort(v+1,v+k+1,[](el a,el b){return a.val<b.val;});
for(int i=1;i<=k;i++)
mi[v[i].x][v[i].y]=i;
for(int i=1;i<=k;i++)
t[i]=-1;
for(int i=1;i<=qsz;i++)
{
int x,y,x2,y2;
fin>>x>>y>>x2>>y2;
query a;
a={x,y,x2,y2,i};
qi[mi[x][y]].insert(a);
qi[mi[x2][y2]].insert(a);
}
for(int i=k;i>=1;i--)
{
vl = v[i].val;
for(auto& j : op[i])
join(i,j);
for(int d=0;d<4;d++)
{
int l= dx[d]+v[i].x;
int c= dy[d]+v[i].y;
if(inmat(l,c) && mi[l][c]<=i)
op[mi[l][c]].push_back(i);
}
}
for(int i=1;i<=qsz;i++)
fout<<sol[i]<<'\n';
}