Cod sursa(job #238293)

Utilizator ProtomanAndrei Purice Protoman Data 1 ianuarie 2009 18:30:38
Problema Struti Scor 70
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.55 kb
#include <stdio.h>
#include <algorithm>
#define mx 1024

using namespace std;

struct coord
{
	short x, y;
} dqmm[mx], dqmn[mx], cdqmm[mx][mx], cdqmn[mx][mx];
short cctmm[mx], cctmn[mx], cstmm[mx], cstmn[mx];
int n, m, p, soll, solc, x, y, lx, ly; 
short stmm, stmn, ctmm, ctmn;
short alt[mx][mx];

inline void cauta()
{
	memset(cdqmm, 0, sizeof(cdqmm));
	memset(cdqmn, 0, sizeof(cdqmn));
	memset(cctmm, 0, sizeof(cctmm));
	memset(cctmn, 0, sizeof(cctmn));
	for (int i = 1 ; i <= m; i++)
		cstmm[i] = cstmn[i] = 1;
	for (int i = 1; i <= n; i++)
	{
		ctmm = ctmn = 0;
		stmm = stmn = 1;
		for (int j = 1; j <= m; j++)
		{
			cdqmm[j][++cctmm[j]].x = cdqmn[j][++cctmn[j]].x = i;
			cdqmm[j][cctmm[j]].y = cdqmn[j][cctmn[j]].y = j;
			for (; cctmm[j] > cstmm[j] 
				&& alt[cdqmm[j][cctmm[j]].x][cdqmm[j][cctmm[j]].y] > alt[cdqmm[j][cctmm[j] - 1].x][cdqmm[j][cctmm[j] - 1].y];
				cctmm[j]--)
				swap(cdqmm[j][cctmm[j]], cdqmm[j][cctmm[j] - 1]);
			if (cdqmm[j][cstmm[j]].x < i + 1 - lx || cdqmm[j][cstmm[j]].y < j + 1 - ly)
				cstmm[j]++;
			for (; cctmn[j] > cstmn[j] 
				&& alt[cdqmn[j][cctmn[j]].x][cdqmn[j][cctmn[j]].y] < alt[cdqmn[j][cctmn[j] - 1].x][cdqmn[j][cctmn[j] - 1].y];
				cctmn[j]--)
				swap(cdqmn[j][cctmn[j]], cdqmn[j][cctmn[j] - 1]);
			if (cdqmn[j][cstmn[j]].x < i + 1 - lx || cdqmn[j][cstmn[j]].y < j + 1 - ly)
				cstmn[j]++;
			dqmm[++ctmm] = cdqmm[j][cstmm[j]];
			dqmn[++ctmn] = cdqmn[j][cstmn[j]];
			for (; ctmm > stmm && alt[dqmm[ctmm].x][dqmm[ctmm].y] > alt[dqmm[ctmm - 1].x][dqmm[ctmm - 1].y]; ctmm--)
				swap(dqmm[ctmm], dqmm[ctmm - 1]);
			if (dqmm[stmm].x < i + 1 - lx || dqmm[stmm].y < j + 1 - ly)
				stmm++;
			for (; ctmn > stmn && alt[dqmn[ctmn].x][dqmn[ctmn].y] < alt[dqmn[ctmn - 1].x][dqmn[ctmn - 1].y]; ctmn--)
				swap(dqmn[ctmn], dqmn[ctmn - 1]);
			if (dqmn[stmn].x < i + 1 - lx || dqmn[stmn].y < j + 1 - ly)
				stmn++;
			int l = alt[dqmm[stmm].x][dqmm[stmm].y] - alt[dqmn[stmn].x][dqmn[stmn].y];
			if (i < lx || j < ly)
				continue;
			if (l < soll)
			{
				soll = l;
				solc = 0;
			}
			if (l == soll)
				solc++;
		}
	}
}

int main()
{
	freopen("struti.in","r",stdin);
	freopen("struti.out","w",stdout);
	scanf("%d %d %d", &n, &m, &p);
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
			scanf("%d", &alt[i][j]);
	for (; p; p--)
	{
		scanf("%d %d", &x, &y);
		soll = LONG_MAX;
		solc = 0;
		lx = x, ly = y;
		cauta();
		if (x != y)
		{
			swap(lx, ly);
			cauta();
		}
		printf("%d %d\n", soll, solc);
	}
	fclose(stdin);
	fclose(stdout);
	return 0;
}