Cod sursa(job #2629511)

Utilizator andreisontea01Andrei Sontea andreisontea01 Data 21 iunie 2020 12:40:36
Problema Struti Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.49 kb
#include <fstream>
#include <deque>

using namespace std;

const int MAXN = 1005;

int harta[MAXN][MAXN], cp[MAXN][MAXN], mini[MAXN][MAXN], maxi[MAXN][MAXN];
deque<int> mn, mx;

int n, m, mind, cnt;

void calc_min(int dx, int dy){
    for(int i = 1; i <= n; ++i){
        mn.clear();
        for(int j = 1; j <= m; ++j){
            while(!mn.empty() && harta[i][mn.back()] > harta[i][j]) mn.pop_back();
            if(!mn.empty() && j - mn.front() + 1 > dy) mn.pop_front();
            mn.push_back(j);
            cp[i][j] = harta[i][mn.front()];
        }
    }
    for(int j = 1; j <= m; ++j){
        mn.clear();
        for(int i = 1; i <= n; ++i){
            while(!mn.empty() && cp[mn.back()][j] > cp[i][j]) mn.pop_back();
            if(!mn.empty() && i - mn.front() + 1 > dx) mn.pop_front();
            mn.push_back(i);
            mini[i][j] = cp[mn.front()][j];
        }
    }
}

void calc_max(int dx, int dy){
    for(int i = 1; i <= n; ++i){
        mx.clear();
        for(int j = 1; j <= m; ++j){
            while(!mx.empty() && harta[i][mx.back()] < harta[i][j]) mx.pop_back();
            if(!mx.empty() && j - mx.front() + 1 > dy) mx.pop_front();
            mx.push_back(j);
            cp[i][j] = harta[i][mx.front()];
        }
    }
    for(int j = 1; j <= m; ++j){
        mx.clear();
        for(int i = 1; i <= n; ++i){
            while(!mx.empty() && cp[mx.back()][j] < cp[i][j]) mx.pop_back();
            if(!mx.empty() && i - mx.front() + 1 > dx) mx.pop_front();
            mx.push_back(i);
            maxi[i][j] = cp[mx.front()][j];
        }
    }
}

void find_best(int dx, int dy){
    calc_min(dx, dy);
    calc_max(dx, dy);
    for(int i = dx; i <= n; ++i){
        for(int j = dy; j <= m; ++j){
            if(maxi[i][j] - mini[i][j] == mind) cnt++;
            if(maxi[i][j] - mini[i][j] < mind){
                mind = maxi[i][j] - mini[i][j];
                cnt = 1;
            }
        }
    }
}

int main()
{
    ifstream fin("struti.in");
    ofstream fout("struti.out");
    ios::sync_with_stdio(false);
    fin.tie(0);
    fout.tie(0);
    int p;
    fin >> n >> m >> p;
    for(int i = 1; i <= n; ++i){
        for(int j = 1; j <= m; ++j)
            fin >> harta[i][j];
    }
    while(p--){
        int dx, dy;
        mind = 1e9; cnt = 1;
        fin >> dx >> dy;
        find_best(dx, dy);
        if(dx != dy) find_best(dy, dx);
        fout << mind << " " << cnt << "\n";
    }
    return 0;
}