Cod sursa(job #1066548)

Utilizator ctlin04UAIC.VlasCatalin ctlin04 Data 24 decembrie 2013 23:45:23
Problema Struti Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.36 kb
#include<fstream>
using namespace std;
typedef struct { int v,poz; } tip;
tip deq[1005];
int i,j,n,m,dx,dy,t,a[1005][1005],minim[1005][1005],maxim[1005][1005],aux[1005][1005],sol,nrsol,cap,coada;

bool cmp(int a, int b, int cr) {
     if (cr==1) {
                if (a>b) return(0); else return(1);
                }
     else {
          if (a>=b) return(1); else return(0);
          }
}

void baga(int val, int poz, int cr) {
     while (cmp(deq[coada].v,val,cr)&&coada>=cap) --coada;
     ++coada; deq[coada].v=val; deq[coada].poz=poz; 
}

void process(int x, int cr) {
     int i,j;
     for (j=1; j<=m; ++j) {
         cap=1; coada=0;
         for (i=1; i<=x; ++i) baga(a[i][j],i,cr);
         aux[x][j]=deq[cap].v;
         for (i=x+1; i<=n; ++i) {
             baga(a[i][j],i,cr);
             if (deq[cap].poz<=i-x) ++cap;
             aux[i][j]=deq[cap].v;
             }
         }
}

void getmax(int x, int y) {
    int i,j;
    process(x,1); 
     for (i=x; i<=n; ++i) {
         cap=1; coada=0;
         for (j=1; j<=y; ++j) baga(aux[i][j],j,1);
         maxim[i][y]=deq[cap].v;
         for (j=y+1; j<=m; ++j) {
             baga(aux[i][j],j,1);
             if (deq[cap].poz<=j-y) ++cap;
             maxim[i][j]=deq[cap].v;
             }
         }
}

void getmin(int x, int y) {
     int i,j;
     process(x,2);
     
     for (i=x; i<=n; ++i) {
         cap=1; coada=0;
         for (j=1; j<=y; ++j) baga(aux[i][j],j,2);
         minim[i][y]=deq[cap].v;
         for (j=y+1; j<=m; ++j) {
             baga(aux[i][j],j,2);
             if (deq[cap].poz<=j-y) ++cap;
             minim[i][j]=deq[cap].v;
             }
         }
} 

void query(int x,int y) {
     int i,j,newsol;
       getmax(x,y);  getmin(x,y);
     for (i=x; i<=n; ++i)
       for (j=y; j<=m; ++j) {
              newsol=maxim[i][j]-minim[i][j];
               if (newsol<sol) { sol=newsol; nrsol=1; }
                 else if (newsol==sol) ++nrsol;
                 }
}
 
int main(void) {
    ifstream fin("struti.in");
    ofstream fout("struti.out");
    fin>>n>>m>>t;
    for (i=1; i<=n; ++i)
     for (j=1; j<=m; ++j) fin>>a[i][j];
    
    for (; t>0; --t) {
        fin>>dx>>dy;
        sol=1000000000; nrsol=0;
        query(dx,dy);
        if (dx!=dy) query(dy,dx);
        fout<<sol<<" "<<nrsol<<"\n";
        }
 return(0);
}