Cod sursa(job #2981184)

Utilizator PsyDuck1914Feraru Rares-Serban PsyDuck1914 Data 17 februarie 2023 14:41:14
Problema Struti Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.83 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <deque>

using namespace std;

ifstream f ("struti.in");
ofstream g ("struti.out");

const int NMAX = 1e3;
int a[NMAX+1][NMAX+1];
vector<deque<int>> vmax(NMAX+1), vmin(NMAX+1);
int hmax[NMAX+1], hmin[NMAX+1];
int n, m, q;

void clear(){
    for(int j=0; j<=NMAX; j++)
        while(!vmax[j].empty())
            vmax[j].pop_back();
    for(int j=0; j<=NMAX; j++)
        while(!vmin[j].empty())
            vmin[j].pop_back();    
}

void liniarizare(int i, int l){
    
    fill(hmax+1, hmax+1+NMAX, 0);
    fill(hmin+1, hmin+1+NMAX, 0);
    for(int j=1; j<=m; j++){
        if(!vmax[j].empty() and vmax[j].front() == i-l)
            vmax[j].pop_front();
        if(!vmin[j].empty() and vmin[j].front() == i-l)
            vmin[j].pop_front();
            
        while(!vmax[j].empty() and a[i][j] >= a[vmax[j].back()][j])
            vmax[j].pop_back();
        while(!vmin[j].empty() and a[i][j] <= a[vmin[j].back()][j])
            vmin[j].pop_back();
            
        vmax[j].push_back(i);
        vmin[j].push_back(i);
        
        hmax[j] = a[vmax[j].front()][j];
        hmin[j] = a[vmin[j].front()][j];
        
        
    }
}

void minimizare(int l, int w, int &mn, int &cnt){
    
    
    for(int i=1; i<=n; i++){
        
        liniarizare(i, l);
        deque<int> mmx, mmn;
        if(i >= l){
            for(int j=1; j<=m; j++){
            
            while(!mmx.empty() and mmx.front() <= j-w)
                mmx.pop_front();
            while(!mmn.empty() and mmn.front() <= j-w)
                mmn.pop_front();
                
            while(!mmx.empty() and hmax[j] >= hmax[mmx.back()])
                mmx.pop_back();
            while(!mmn.empty() and hmin[j] <= hmin[mmn.back()])
                mmn.pop_back();
                
            mmn.push_back(j);
            mmx.push_back(j);
            
            if(j >= w){
                 if(mn > hmax[mmx.front()] -  hmin[mmn.front()])
                    mn = hmax[mmx.front()] - hmin[mmn.front()], cnt = 1;
                else if(mn == hmax[mmx.front()] - hmin[mmn.front()])
                        cnt ++;
                
                
            }

        }
        }
        
        
    }
}

int main()
{
    f >> n >> m >> q;
    
    for(int i=1; i<=n; i++)
        for(int j=1; j<=m; j++)
            f >> a[i][j];
    
    for(int y=1; y<=q; y++){
        int dx, dy;
        f >> dx >> dy;
        
        int mn = 1e9;
        int cnt = 0;
        
        clear();
        minimizare(dx, dy, mn, cnt);
        
        clear();
        minimizare(dy, dx, mn, cnt);
        if(dx == dy)
            cnt /= 2;
        g << mn << ' ' << cnt << "\n";
        
        
    }
    
    return 0;
}