Cod sursa(job #1076316)

Utilizator narcis_vsGemene Narcis - Gabriel narcis_vs Data 10 ianuarie 2014 01:02:50
Problema Struti Scor 80
Compilator cpp Status done
Runda Teme Pregatire ACM Unibuc 2013 Marime 2.51 kb
#include <fstream>
#include <deque>
#define LIM 500000
#define NEXT ++pos == LIM ? f.read(Buffer,LIM),pos = 0 : 0
using namespace std;
const int Nmax = 1004;
struct Coord{
    int x, y ;
    Coord(){
        x = y = 0;
    }
    inline Coord(const int _x,const int _y){
        x = _x; y = _y;
    }
};
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() && a[D.back().x][D.back().y] <= x; D.pop_back());
    D.push_back(Coord(i,j));
}
inline void InsertDmin(deque < Coord >&D,const int i,const int j){
    int x = a[i][j];
    for( ; !D.empty() && a[D.back().x][D.back().y] >= x; D.pop_back());
    D.push_back(Coord(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[Nmax], D_min[Nmax];
    for(i = 1;i <= N; ++i){
        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[i],Dmax[j].front().x,Dmax[j].front().y);
                InsertDmin(D_min[i],Dmin[j].front().x,Dmin[j].front().y);
                Pop(D_max[i],j-y,0);
                Pop(D_min[i],j-y,0);
                if(i >= x && j >= y){
                    diff = a[D_max[i].front().x][D_max[i].front().y] - a[D_min[i].front().x][D_min[i].front().y];
                    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;
}