Cod sursa(job #464749)

Utilizator AndreyPAndrei Poenaru AndreyP Data 21 iunie 2010 16:39:05
Problema Struti Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.67 kb
#include <cstdio>
#define N 1001

short m,n,T;
short a[N][N];
short d1[N],d2[N];
short p1,u1,p2,u2;
short min[N][N],max[N][N];
char c[6010];
short rez1;
int rez2;

inline void citire()
{
	scanf("%hd%hd%hd\n",&m,&n,&T);
	short x;
	int t;
	for(short i=1; i<=m; ++i)
	{
		fgets(c,6010,stdin);
		t=0;
		for(short j=1; j<=n; ++j)
		{
			x=0;
			for(; c[t]>='0' && c[t]<='9'; ++t)
				x=x*10+(c[t]-'0');
			++t;
			a[i][j]=x;
		}
	}
}

inline void rezolva(short dx,short dy)
{
	for(short i=1; i<=m; ++i)
	{
		p1=p2=1;
		u1=u2=0;
		for(short j=1; j<=n; ++j)
		{
			if(p1<=u1 && j-d1[p1]==dy)
				++p1;
			while(p1<=u1 && a[i][d1[u1]]>=a[i][j])
				--u1;
			d1[++u1]=j;

			if(p2<=u2 && j-d2[p2]==dy)
				++p2;
			while(p2<=u2 && a[i][d2[u2]]<=a[i][j])
				--u2;
			d2[++u2]=j;
			min[i][j]=a[i][d1[p1]];
			max[i][j]=a[i][d2[p2]];
		}
	}

	short aux;
	for(short j=dy; j<=n; ++j)
	{
		p1=p2=1;
		u1=u2=0;
		for(short i=1; i<=m; ++i)
		{
			if(p1<=u1 && i-d1[p1]==dx)
				++p1;
			while(p1<=u1 && min[d1[u1]][j]>=min[i][j])
				--u1;
			d1[++u1]=i;

			if(p2<=u2 && i-d2[p2]==dx)
				++p2;
			while(p2<=u2 && max[d2[u2]][j]<=max[i][j])
				--u2;
			d2[++u2]=i;

			if(i<dx)
				continue;
			aux=max[d2[p2]][j]-min[d1[p1]][j];
			if(aux<rez1)
			{
				rez1=aux;
				rez2=1;
			}
			else
			if(aux==rez1)
				++rez2;
		}
	}
}
			
int main()
{
	freopen("struti.in","r",stdin);
	freopen("struti.out","w",stdout);

	citire();
	short dx,dy;
	for(short i=0; i<T; ++i)
	{
		scanf("%hd%hd",&dx,&dy);
		rez1=20010;
		rez2=0;
		rezolva(dx,dy);
		if(dx!=dy)
			rezolva(dy,dx);
		printf("%hd %d\n",rez1,rez2);
	}

	return 0;
}