Cod sursa(job #424398)

Utilizator ciprianfFarcasanu Alexandru Ciprian ciprianf Data 24 martie 2010 20:27:28
Problema Matrice 2 Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.18 kb
#include <stdio.h>
#include <algorithm>
using namespace std;
#define NMAX 100000
#define MOD 301
#define INF 2000000000
struct xy{
	int x, y, p, sol;
};
struct comp{
	bool operator()(const xy &a, const xy &b){
		if(a.y == b.y) return a.x < b.x;
		return a.y > b.y;
	}
};
struct comp2{
	bool operator()(const xy &a, const xy &b){
		return a.sol > b. sol;
	}
};
const int lin[]={0,0,1,-1};
const int col[]={1,-1,0,0};
xy v[NMAX], w[20010], cop[20010];
int ans[20010];
int A[MOD][MOD];
int T[NMAX], RG[NMAX];
int n, k, hmax ;
int find(int x){
	if(T[x] != x)
		T[x] = find(T[x]);
	return T[x];
}
void unire(int x, int y){
	if(RG[x] > RG[y])
		T[y] = x;
	else T[x] = y;
	if(RG[x] == RG[y]) RG[y]++;
}
void vecini(int nod, int h){
	int x = nod/MOD, y = nod%MOD;
	int p;
	for(int t = 0; t < 4; ++t)
		if(A[x+lin[t]][y+col[t]] >= h){
			p = (x+lin[t])*MOD + y+col[t];
			if(find(nod) != find(p))
				unire(find(nod), find(p));
		}
}
void solve(){
	int h;
	for(h = 1; h <= hmax; h <<= 1); 
	h >>= 1;
	for(; h; h >>= 1){
		for(int i = 1; i <= v[0].x; ++i)
			T[v[i].x] = v[i].x;
		for(int i = 1; i <= k; ++i)
			w[i].sol += h-1;
		int poz = 1;
		int j;
		for(int i = 1; i <= v[0].x && poz <= k; ++i){
			for(j = i; i <= v[0].x && v[i].y == v[j].y; ++i)
				vecini(v[i].x, v[i].y);
			
			while(poz <= k && w[poz].sol > v[i].y){
				if(find(w[poz].x) != find(w[poz].y)) w[poz].sol -= h-1;
				else w[poz].sol ++;
				poz++;
			}
			i--;
		}
		sort(w + 1, w + k + 1, comp2());
	}
}
int main(){
	freopen("matrice2.in", "r", stdin);
	freopen("matrice2.out", "w", stdout);
	scanf("%d%d", &n, &k);
	
	for(int i = 1; i <= n; ++i)
		for(int j = 1; j <= n; ++j){
			v[++v[0].x].x = i*MOD + j;
			scanf("%d", &v[v[0].x].y);
			A[i][j] = v[v[0].x].y;
			if(v[v[0].x].y > hmax) hmax = v[v[0].x].y;
		}
	sort(v + 1, v + v[0].x + 1, comp());
	for(int i = 1; i <= k; ++i){
		int x1, y1, x2, y2;
		scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
		w[i].x = x1*MOD + y1;
		w[i].y = x2*MOD + y2;
		w[i].p = i;
	}
	//v[n+1].y = INF;
	solve();
	for(int i = 1; i <= k; ++i)
		ans[w[i].p] = w[i].sol;
	for(int i = 1; i <= k; ++i)
		printf("%d\n", ans[i]-1);
	return 0;
}