Cod sursa(job #253055)

Utilizator bogdanhm999Casu-Pop Bogdan bogdanhm999 Data 5 februarie 2009 13:19:51
Problema Struti Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.8 kb
#include <stdio.h>
#include <string>
short int n,m,Q,i,j,k,l,sol,nrsol,Smin[1024],Smax[1024],Pmin[1024],Pmax[1024],dx[12],dy[12];
short int a[1001][1024],deq1min[1001][1024],deq1max[1001][1024];
short int deq2min[1001][1024],deq2max[1001][1024],p,q,st,dr,L,U;
char ch[5005];

void read(){
  freopen("struti.in","r",stdin);freopen("struti.out","w",stdout);
	scanf("%d %d %d\n",&n,&m,&Q);
	for (i=1;i<=n;++i){
		gets(ch); l=strlen(ch); ch[l]=' '; k=0;
		for (j=1;j<=m;++j){
			short int x=0;
		  while (ch[k]!=' '){x=x*10+ch[k]-'0';k++;}
			a[i][j]=x;k++;
	  }
	}
	for (i=1;i<=Q;++i)scanf("%d %d",&dx[i],&dy[i]);
}
int main(){
	read();
	for (k=1;k<=Q;++k){
		L=dx[k]; U=dy[k];
		//deque pe linii
		for (i=1;i<=n;++i){
			 p=1;q=0; st=1;dr=0;
			 for (j=1;j<=m;++j){
					//minimul
					while (q>=p && a[i][j]<Smin[q])q--;
					q++; Smin[q]=a[i][j]; Pmin[q]=j;
					while (p<q && Pmin[p]+U <= j)p++;
					deq1min[i][j]=Smin[p];
					//maximul
					while (dr>=st && a[i][j]>Smax[dr])dr--;
					dr++; Smax[dr]=a[i][j];Pmax[dr]=j;
					while (st<dr && Pmax[st]+U <= j)st++;
					deq1max[i][j]=Smax[st];
			 }
		}
		//deque pe coloane
		for (j=U;j<=m;++j){
			 p=1;q=0; st=1;dr=0;
		   for (i=1;i<=n;++i){
					//minimul
					while (q>=p && deq1min[i][j]<Smin[q])q--;
					q++; Smin[q]=deq1min[i][j]; Pmin[q]=j;
					while (p<q && Pmin[p]+L <= j)p++;
					deq2min[i][j]=Smin[p];
					//maximul
					while (dr>=st && deq1max[i][j]>Smax[dr])dr--;
					dr++; Smax[dr]=deq1max[i][j];Pmax[dr]=j;
					while (st<dr && Pmax[st]+L <= j)st++;
					deq2max[i][j]=Smax[st];
			 }
	  }
		sol=10000;
		for (i=L;i<=n;++i)
			 for (j=U;j<=m;++j){
					q=deq2max[i][j]-deq2min[i][j];
				  if (q<sol){sol=q;nrsol=1;}
					else if (q==sol)nrsol++;
			 }
	 printf("%d %d\n",sol,nrsol);
 }
return 0;
}