Pagini recente » Cod sursa (job #1165311) | Cod sursa (job #2383927) | Cod sursa (job #1282827) | Cod sursa (job #2381798) | Cod sursa (job #1086451)
#include <iostream>
#include <fstream>
#include <algorithm>
#define MAX_N 310
#define MAX_NM 90010
#define MAX_Q 20010
using namespace std;
int n,q,L;
char B[MAX_N][MAX_N];
int W[MAX_N][MAX_N];
int X[MAX_NM], Y[MAX_NM], C[MAX_NM], P[MAX_NM];
int G[MAX_NM];
int rasp[MAX_Q];
int Query[MAX_Q], P2[MAX_Q];
int X1[MAX_Q], Y1[MAX_Q], X2[MAX_Q], Y2[MAX_Q];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
inline int cmp(int x, int y)
{
return C[x] > C[y];
}
inline int cmp2(int x, int y)
{
return Query[x] > Query[y];
}
inline int father(int x)
{
if (x != G[x]) G[x] = father(G[x]);
return G[x];
}
int main()
{
int i, j, k, p, pas, cx, cy;
ifstream f("matrice2.in");
ofstream g("matrice2.out");
f >>n>>q;
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
{
L++;
W[i][j] = L;
X[L] = i, Y[L] = j;
f >> C[L];
P[L] = L;
}
for (i=1;i<=q;i++)
f >> X1[i] >> Y1[i] >> X2[i] >> Y2[i];
sort(P+1, P+L+1, cmp);
pas=1;
while(pas<C[P[1]])
pas=(pas<<1);
while(pas>0)
{
for (i = 1; i <= q; i++)
{
Query[i] = rasp[i] + pas;
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 (father( W[X1[P2[j]]][Y1[P2[j]]] ) == father( W[X2[P2[j]]][Y2[P2[j]]] ))
rasp[P2[j]] += pas;
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]] + dx[p];
cy = Y[P[i]] + dy[p];
if (cx > 0 && cy > 0 && cx <= n && cy <= n && B[cx][cy])
G[G[ father(W[cx][cy]) ]] = G[P[i]];
}
}
}
while(j<=q){
if (father( W[X1[P2[j]]][Y1[P2[j]]] ) == father( W[X2[P2[j]]][Y2[P2[j]]] ))
rasp[P2[j]] += pas;
j++;
}
pas=pas/2;
}
for (i = 1; i <= q; i++)
g<<rasp[i]<<'\n';
return 0;
}