Cod sursa(job #1076296)

Utilizator narcis_vsGemene Narcis - Gabriel narcis_vs Data 10 ianuarie 2014 00:39:50
Problema Struti Scor 30
Compilator cpp Status done
Runda Teme Pregatire ACM Unibuc 2013 Marime 2.22 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){
    for( ;  D.front().x <= x;D.pop_front());
}

inline void Solve(const int x,const int y){
    int i, j, diff,Left = 1, Right = y;
    deque < Coord > Dmax, Dmin;
    for(  ; Right <= M; ++Left,++Right){
        Dmax.clear();
        Dmin.clear();
        for(i = 1;i <= N; ++i){
            for( j = Left; j <= Right; ++j){
                InsertDmax(Dmax,i,j);
                InsertDmin(Dmin,i,j);
            }
            if(i >= x)
            {
                Pop(Dmax,i-x);
                Pop(Dmin,i-x);
                diff = a[Dmax.front().x][Dmax.front().y] - a[Dmin.front().x][Dmin.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;
}