Cod sursa(job #326407)

Utilizator ProtomanAndrei Purice Protoman Data 24 iunie 2009 22:00:36
Problema Struti Scor 70
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.37 kb
#include <stdio.h>
#include <algorithm>
#define mx 1024

using namespace std;

struct coord
{
	short x, y;
}; 
int n, m, p, x, y, soll, solc; 
short stmm, stmn, ctmm, ctmn;
short alt[mx][mx];
short cdqmm[mx][mx], cdqmn[mx][mx];

inline void cauta(int lx, int ly)
{
	coord dqmm[mx], dqmn[mx];
	short cctmm[mx], cctmn[mx], cstmm[mx], cstmn[mx];

	for (int i = 1 ; i <= m; ++i)
	{
		cstmm[i] = cstmn[i] = 1;
		cctmm[i] = cctmn[i] = 0;
	}
	for (int i = 1; i <= n; ++i)
	{
		ctmm = ctmn = 0;
		stmm = stmn = 1;
		for (int j = 1; j <= m; ++j)
		{

			// update deque pe coloane

			int el = alt[i][j];
			if (cstmm[j] <= cctmm[j] && cdqmm[j][cstmm[j]] < i + 1 - lx)
				cstmm[j]++;
			for (; cctmm[j] >= cstmm[j] && el > alt[cdqmm[j][cctmm[j]]][j]; --cctmm[j]);
			if (cstmn[j] <= cctmn[j] && cdqmn[j][cstmn[j]] < i + 1 - lx)
				cstmn[j]++;
			for (; cctmn[j] >= cstmn[j] && el < alt[cdqmn[j][cctmn[j]]][j]; --cctmn[j]);
			cdqmm[j][++cctmm[j]] = cdqmn[j][++cctmn[j]] = i;

			// update deque pe dreptunghi

			el = alt[cdqmm[j][cstmm[j]]][j];
			if (stmm <= ctmm && dqmm[stmm].y < j + 1 - ly)
				stmm++;
			for (; ctmm >= stmm && el > alt[dqmm[ctmm].x][dqmm[ctmm].y]; --ctmm);
			if (stmn <= ctmn && dqmn[stmn].y < j + 1 - ly)
				stmn++;
			el = alt[cdqmn[j][cstmn[j]]][j];
			for (; ctmn >= stmn && el < alt[dqmn[ctmn].x][dqmn[ctmn].y]; --ctmn);
			dqmm[++ctmm].x = cdqmm[j][cstmm[j]];   
            dqmn[++ctmn].x = cdqmn[j][cstmn[j]];   
            dqmm[ctmm].y = dqmn[ctmn].y = j; 
			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", &n, &m, &p);
	for (int i = 1; i <= n; ++i)
	{
		char s[6000];
		fgets(s, 6000, stdin);   
		int x = 0, xx = strlen(s);   
		for (int id = 0, j = 0; id <= xx; ++id)   
			if ('0' <= s[id] && s[id] <= '9')   
				x = x * 10 + s[id] - '0';   
			else   
			{   
				alt[i][++j] = x;   
				x = 0;   
			}   
    }   
	for (; p; p--)
	{
		scanf("%d %d", &x, &y);
		soll = LONG_MAX;
		solc = 0;
		cauta(x, y);
		if (x != y)
			cauta(y, x);
		printf("%d %d\n", soll, solc);
	}
	fclose(stdin);
	fclose(stdout);
	return 0;
}