Cod sursa(job #916273)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 16 martie 2013 10:58:09
Problema Struti Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.32 kb
#include <fstream>
#include <deque>

using namespace std;

const int MAX_N = 1003;

int N, M, P, R, C, Sol;
int Nr, A[ MAX_N ][ MAX_N ], Min[ MAX_N ][ MAX_N ], Max[ MAX_N ][ MAX_N ];
deque < int > a, b;

inline int solve(int R, int C);

int main()
{
    ifstream cin("struti.in");
    ofstream cout("struti.out");
    cin>>N>>M>>P;
    for(int i=1 ; i<=N ; ++i)
        for(int j=1; j<=M ; ++j)
            cin>>A[i][j];
    for(;P;)
    {
        Sol=((1<<31)-1);
        Nr=0;
        cin>>R>>C;
        solve(R, C);
        if(!(R==C))
        {
            solve(C, R);
        }
        --P;
        cout<<Sol<<" "<<Nr<<"\n";
    }
    return 0;
}

inline int solve(int R, int C)
{
    a.clear();
    b.clear();
    for(int i=1; i<=N; ++i)
    {
        a.clear();
        b.clear();
        for(int j=1; j<=M; ++j)
            {
                while(!a.empty() && A[i][j]<=A[i][a.back()])
                    a.pop_back();
                a.push_back(j);
                if(a.front() <= j-C)
                    a.pop_front();
                if(j >= C)
                    Min[i][j]=A[i][a.front()];
                while(!b.empty() && A[i][j]>=A[i][b.back()])
                    b.pop_back();
                b.push_back(j);
                if(b.front() <= j-C)
                    b.pop_front();
                if(j >= C)
                    Max[i][j]=A[i][b.front()];
            }

    }
    for(int j=C; j<=M; ++j)
        {
            a.clear();
            b.clear();
            for(int i=1; i<=N; ++i)
            {
                while(!a.empty() && Min[i][j]<=Min[a.back()][j])
                    a.pop_back();
                a.push_back(i);
                if(a.front() <= i-R)
                    a.pop_front();
                while(!b.empty() && Max[i][j]>=Max[b.back()][j])
                    b.pop_back();
                b.push_back(i);
                if(b.front() <= i-R)
                    b.pop_front();
                if(i >= R)
                {
                    if(Max[b.front()][j]-Min[a.front()][j] < Sol)
                            Sol = Max[b.front()][j]-Min[a.front()][j], Nr = 1;
                        else if(Max[b.front()][j]-Min[a.front()][j] == Sol)
                                ++Nr;
                }
            }
        }
}