Cod sursa(job #935366)

Utilizator rudarelLup Ionut rudarel Data 3 aprilie 2013 09:02:23
Problema Struti Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.65 kb
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <deque>
using namespace std;
 
#define SIRMAX 70000
#define FOR(i, a, b)    for(int i = a ; i <= b ; i++)
 
const int INF = 1500000000;
const int NMAX = 1011;
const int MMAX = 1011;
int A[NMAX][MMAX];
int N, M, P;
int NR = 0, val;
int m[NMAX][MMAX];
int MX[NMAX][MMAX];
 
void parsare()
{
    scanf("%d%d%d\n",&M,&N,&P);
    FOR(i, 1, M)
        FOR(j, 1, N)
            scanf("%d", &A[i][j]);
}
 
int linii(int x, int y)
{
    deque<int> D;
    deque<int> d;
     
    for(int j = x ; j <= N ; j++)
    {
        for(int i = 1 ; i <= M ; i++)
        {          
            while(D.size() && MX[D.back()][j] <= MX[i][j])
                    D.pop_back();
            D.push_back(i);
            if(D.front() <= i - y)
                D.pop_front();
             
            while(d.size() && m[d.back()][j] >= m[i][j])
                    d.pop_back();
            d.push_back(i);
            if(d.front() <= i - y)
                d.pop_front();
             
            if(i >= y)
                if(MX[D.front()][j] - m[d.front()][j] < val)
                {
                    val = MX[D.front()][j] - m[d.front()][j];
                    NR = 1;
                }
                else if(MX[D.front()][j] - m[d.front()][j] == val)
                    NR++;
        }
        D.clear();
        d.clear();
    }
     
    return val;
}
 
void dq(int x)
{
    deque<int> st[MMAX];
    deque<int> ST[MMAX];
     
    for(int i = 1 ; i <= M ; i++)
        for(int j = 1 ; j <= N ; j++)
        {
            while(ST[i].size() && A[i][ST[i].back()] <= A[i][j])
                ST[i].pop_back();
            ST[i].push_back(j);        
            while(ST[i].front() <= j - x)
                ST[i].pop_front();
 
            while(st[i].size() && A[i][st[i].back()] >= A[i][j])
                st[i].pop_back();
            st[i].push_back(j);        
            while(st[i].front() <= j - x)
                st[i].pop_front();
             
            if(j >= x)
            {
                MX[i][j] = A[i][ST[i].front()];
                m[i][j] = A[i][st[i].front()];
            }
        }
}
 
int main()
{
    int x, y;
    freopen("struti.in","r",stdin);
    freopen("struti.out","w",stdout);
     
    parsare();
         
    for(int k = 1 ; k <= P ; k++)
    {
        NR = 0;
        val = INF;
        scanf("%d%d",&x,&y);
        dq(x);
        linii(x, y);
        if(x != y)
        {
            dq(y);
            linii(y, x);
        }
        printf("%d %d\n",val, NR);
    }
     
    return 0;
}