Pagini recente » Cod sursa (job #185334) | Cod sursa (job #581553)
Cod sursa(job #581553)
#include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;
#define MAXN 305
#define MAXQ 20010
int N, Q, L;
int cx,cy,i,step,k,p,j;
char B[MAXN][MAXN];
int W[MAXN][MAXN];
int X[MAXN*MAXN], Y[MAXN*MAXN], C[MAXN*MAXN], P[MAXN*MAXN];
int G[MAXN*MAXN];
int Sol[MAXQ];
int Query[MAXQ], P2[MAXQ];
int X1[MAXQ], Y1[MAXQ], X2[MAXQ], Y2[MAXQ];
int dirx[4] = {-1, 0, 1, 0};
int diry[4] = {0, 1, 0, -1};
int rad(int nod)
{
if (G[nod] == nod) return nod;
G[nod] = rad(G[nod]);
return G[nod];
}
inline bool cmp(const int &x, const int &y)
{ return C[x] > C[y]; }
inline bool cmp2(const int &x, const int &y)
{ return Query[x] > Query[y]; }
int main()
{
freopen("matrice2.in","r",stdin);
freopen("matrice2.out","w",stdout);
scanf("%d %d",&N,&Q);
L = 0;
for (i=1; i<=N; ++i)
for (j=1; j<=N; ++j){
++L;
W[i][j] = L;
X[L] = i; Y[L] = j;
scanf("%d", &C[L]);
P[L] = L;
}
sort(P+1, P+L+1, cmp);
for (i=1; i<=Q; ++i)
scanf("%d %d %d %d",&X1[i], &Y1[i], &X2[i], &Y2[i]);
for (step = 1; step < C[P[1]]; step <<= 1);
for (; step; step >>= 1)
{
for (i = 1; i <= Q; i++)
{
Query[i] = Sol[i] + step;
P2[i] = i;
}
sort(P2+1, P2+Q+1, cmp2);
for (i = 1; i <= L; i++) G[i] = i;
for (i = 1; i <= N; i++)
for (j = 1; j <= N; j++) B[i][j] = 0;
for (i = 1, j = 1; i <= L; )
{
for (k = j; j <= Q && Query[P2[j]] > C[P[i]]; j++)
if (rad( W[X1[P2[j]]][Y1[P2[j]]] ) == rad( W[X2[P2[j]]][Y2[P2[j]]] )) Sol[P2[j]] += step;
for (k = i; i <= L && C[P[i]] == C[P[k]]; i++)
{
B[X[P[i]]][Y[P[i]]] = 1;
for (p = 0; p < 4; p++)
{
cx = X[P[i]] + dirx[p];
cy = Y[P[i]] + diry[p];
if (cx > 0 && cy > 0 && cx <= N && cy <= N && B[cx][cy])
G[G[ rad(W[cx][cy]) ]] = G[P[i]];
}
}
}
for (; j <= Q; j++)
if (rad( W[X1[P2[j]]][Y1[P2[j]]] ) == rad( W[X2[P2[j]]][Y2[P2[j]]] )) Sol[P2[j]] += step;
}
for (i=1; i<=Q; ++i)
printf("%d\n", Sol[i]);
return 0;
}