Cod sursa(job #1076328)

Utilizator narcis_vsGemene Narcis - Gabriel narcis_vs Data 10 ianuarie 2014 01:18:38
Problema Struti Scor 80
Compilator cpp Status done
Runda Teme Pregatire ACM Unibuc 2013 Marime 2.64 kb
#include <fstream>
#include <deque>
#define LIM 5000000
#define NEXT ++pos == LIM ? f.read(Buffer,LIM),pos = 0 : 0
using namespace std;
const int Nmax = 1004;
struct Coord{
    int x, y ,val;
    Coord(){
        x = y = 0;
    }
    inline Coord(const int _x,const int _y,const int _val){
        x = _x; y = _y;val = _val;
    }
};
int pos, N, M , P , sol, cnt;
char Buffer[LIM];
int a[Nmax][Nmax];
ifstream f("struti.in");
ofstream g("struti.out");
inline void Read(int &x){
    for( ; Buffer[pos] < '0' || '9' < Buffer[pos]; NEXT);
    for(x = 0 ;'0' <= Buffer[pos] && Buffer[pos] <= '9'; NEXT)
        x = x * 10 + Buffer[pos]-'0';
}

inline void InsertDmax(deque < Coord >&D,const int i,const int j){
    int x = a[i][j];
    for( ; !D.empty() && D.back().val <= x; D.pop_back());
    D.push_back(Coord(i,j,a[i][j]));
}
inline void InsertDmin(deque < Coord >&D,const int i,const int j){
    int x = a[i][j];
    for( ; !D.empty() && D.back().val >= x; D.pop_back());
    D.push_back(Coord(i,j,a[i][j]));
}
inline void Pop(deque < Coord > &D,const int x,const bool flag){
    if(flag)
        for( ;  D.front().x == x; D.pop_front());
    else
        for( ;  D.front().y == x; D.pop_front());
}

inline void Solve(const int x,const int y){
    int i, j,diff ;
    deque < Coord > Dmax[Nmax], Dmin[Nmax] , D_max, D_min;
    for(i = 1;i < x; ++i)
        for( j = 1; j <= M; ++j){
            InsertDmax(Dmax[j],i,j);
            InsertDmin(Dmin[j],i,j);
        }
    for(i = x;i <= N; ++i){
        D_max.clear();
        D_min.clear();
        for( j = 1; j <= M; ++j){
                InsertDmax(Dmax[j],i,j);
                InsertDmin(Dmin[j],i,j);
                Pop(Dmax[j],i-x,1);
                Pop(Dmin[j],i-x,1);
                InsertDmax(D_max,Dmax[j].front().x,Dmax[j].front().y);
                InsertDmin(D_min,Dmin[j].front().x,Dmin[j].front().y);
                if(j >= y){
                    Pop(D_max,j-y,0);
                    Pop(D_min,j-y,0);
                    diff = D_max.front().val - D_min.front().val;
                    if(diff < sol){
                        sol = diff;
                        cnt = 1;
                    }
                    else
                        if(sol == diff)
                            ++cnt;
                }
            }
    }
}

int main(){
    int i, j, X  , Y;
    f.read(Buffer,LIM);
    Read(N);Read(M);Read(P);
    for( i = 1; i <= N ;++i)
       for( j = 1 ; j <= M; ++j)
             Read(a[i][j]);
    for( ;  P ; --P){
        sol = 100000;
        Read(X);Read(Y);
        Solve(X,Y);
        if(X != Y)
            Solve(Y,X);
        g<<sol<<" "<<cnt<<"\n";
    }
    f.close();
    g.close();
    return 0;
}