Cod sursa(job #2809220)

Utilizator AndreiBOTOBotocan Andrei AndreiBOTO Data 26 noiembrie 2021 12:36:16
Problema Struti Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.48 kb
#include <iostream>
#include <fstream>
#include <deque>
#include <iomanip>

using namespace std;

ifstream fin ("struti.in");
ofstream fout ("struti.out");

const int NMAX=1005;
const int INF=1e4+5;

int d[NMAX*NMAX],dmax[NMAX*NMAX],dmin[NMAX*NMAX];
int lin,col,a[NMAX][NMAX],minim[NMAX][NMAX],maxim[NMAX][NMAX];


void colmin(int col,int dy)
{
    int i,st=0,dr=-1;
    for(i=0;i<lin;i++)
    {
        if(st<=dr && d[st]==i-dy)
            st++;
        while(st<=dr && a[d[dr]][col]>=a[i][col])
            dr--;
        d[++dr]=i;
        minim[i][col]=a[d[st]][col];
    }
}

void colmax(int col,int dy)
{
    int i,st=0,dr=-1;
    for (i=0;i<lin;i++)
    {
        if (st<=dr && d[st]==i-dy)
            st++;
        while(st<=dr && a[d[dr]][col]<=a[i][col])
            dr--;
        d[++dr]=i;
        maxim[i][col]=a[d[st]][col];
    }
}

void amin(int dy)
{
    int i;
    for(i=0;i<col;i++)
        colmin(i,dy);
}

void amax(int dy)
{
    int i;
    for(i=0;i<col;i++)
        colmax(i,dy);
}

void get_diff(int dx,int dy,int &dminim,int &nrnou)
{
    int i,j,stmax=0,drmax=-1,stmin=0,drmin=-1,rez;
    amin(dy);
    amax(dy);
    for(i=dy-1;i<lin;i++)
    {
        stmax=stmin=0;
        drmax=drmin=-1;
        for (j=0;j<col;j++)
        {
            if(stmin<=drmin && dmin[stmin]==j-dx)
                stmin++;
            while(stmin<=drmin && minim[i][dmin[drmin]]>=minim[i][j])
                drmin--;
            dmin[++drmin]=j;
            if (stmax<=drmax && dmax[stmax]==j-dx)
                stmax++;
            while(stmax<=drmax && maxim[i][dmax[drmax]]<=maxim[i][j])
                drmax--;
            dmax[++drmax]=j;
            if (j<dx-1)
                continue;
            int rez=maxim[i][dmax[stmax]] - minim[i][dmin[stmin]];
            if (rez<dminim)
            {
                dminim = rez;
                nrnou=1;
            }
            else if (rez == dminim)
            {
                nrnou++;
            }
        }
    }
}

void afis(int dx,int dy)
{
    int nou,dif=INF;
    get_diff(dx,dy,dif,nou);
    if(dx!=dy)
        get_diff(dy,dx,dif,nou);
    fout<<dif<<" "<<nou<<"\n";
}

int main()
{
    int p,i,j,dx,dy;
    fin>>lin>>col>>p;
    for (i=0;i<lin;i++)
    {
        for (j=0;j<col;j++)
        {
            fin>>a[i][j];
        }
    }
    for (i = 0; i < p; i++)
    {
        fin>>dx>>dy;
        afis(dx, dy);
    }
    return 0;
}