Pagini recente » Cod sursa (job #3153463) | Cod sursa (job #1753232) | Rezultatele filtrării | Cod sursa (job #2786979) | Cod sursa (job #3136987)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("matrice2.in");
ofstream fout("matrice2.out");
struct Query{
int a, b, c, d, st, dr;
}q[20001];
vector<int> vec[90001];
vector<pair<int, int> > v[90001];
int n, k, x[301][301], y[90001], t[90001], sol[20001], di[]={-1, 0, 0, 1}, dj[]={0, -1, 1, 0};
set<int> S;
void Clear()
{for(int i=1;i<=n*n;i++)
t[i]=i;
for(int i=1;i<=k;i++)
vec[i].clear();
}
int R(int a)
{if(a==t[a])return a;
else return t[a]=R(t[a]);
}
void L(int a, int b)
{if(t[a]>t[b])t[b]=t[a];
else t[a]=t[b];
}
void F(int k)
{for(int l=0;l<v[k].size();l++)
{int i=v[k][l].first, j=v[k][l].second;
for(int g=0;g<4;g++)
{int iv=i+di[g], jv=j+dj[g];
if(iv>0 && jv>0 && iv<=n && jv<=n && x[i][j]<=x[iv][jv])
L((i-1)*n+j, (iv-1)*n+jv);
}
}
}
int main()
{ int m;
fin>>n>>m;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{fin>>x[i][j];
S.insert(x[i][j]);
}
set<int>:: iterator I;
for(I=S.begin();I!=S.end();I++)
y[++k]=*I;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{x[i][j]=lower_bound(y+1, y+1+k, x[i][j])-y;
v[x[i][j]].push_back({i, j});
}
for(int i=1;i<=m;i++)
{fin>>q[i].a>>q[i].b>>q[i].c>>q[i].d;
q[i].st=1, q[i].dr=k;
}
for(int l=1;l<=k;l*=2)
{Clear();
for(int i=1;i<=m;i++)
if(q[i].st<=q[i].dr)
vec[(q[i].st+q[i].dr)/2].push_back(i);
for(int i=k;i>0;i--)
{F(i);
for(vector<int>:: iterator I=vec[i].begin();I<vec[i].end();I++)
{int a=(q[*I].a-1)*n+q[*I].b, b=(q[*I].c-1)*n+q[*I].d, st=q[*I].st, dr=q[*I].dr;
if(R(a)==R(b))
{sol[*I]=i;
q[*I].st=i+1;
}
else q[*I].dr=i-1;
}
}
}
for(int i=1;i<=m;i++)
fout<<y[sol[i]]<<"\n";
return 0;
}