Cod sursa(job #669973)

Utilizator SpiderManSimoiu Robert SpiderMan Data 28 ianuarie 2012 09:18:01
Problema Struti Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.14 kb
# include <cstdio>

# define verf ++poz == hg ? fread ( ch, 1, hg, stdin ), poz = 0 : 0

const char *FIN = "struti.in", *FOU = "struti.out";
const int MAX = 1005, oo = 0x3f3f3f3f, hg = 1 << 13;

int mini[MAX], maxi[MAX], A[MAX][MAX], minm[MAX][MAX], maxm[MAX][MAX];
int N, M, T, stm, stM, drm, drM, poz;
char ch[hg];

inline void cit ( int &x ) {
    if ( ch[0] == '\0' ) fread ( ch, 1, hg, stdin ) ;
    else for ( ; ch[poz] < '0' || ch[poz] > '9' ; verf ) ;
    for ( x = 0 ; ch[poz] >= '0' && ch[poz] <= '9' ; x = x * 10 + ch[poz] - '0', verf ) ;
}

inline void solve (int x, int y, int &MIN, int &NR) {
    for (int i = 1; i <= M; ++i) {
        stm = stM = 1, drm = drM = 0;
        for (int j = 1; j <= N; ++j) {
            for (; stm <= drm && A[i][j] < A[i][mini[drm]]; --drm);
            for (; stM <= drM && A[i][j] > A[i][maxi[drM]]; --drM);
            mini[++drm] = maxi[++drM] = j;

            if (mini[stm] <= j - x) ++stm;
            if (maxi[stM] <= j - x) ++stM;

            minm[i][j] = A[i][mini[stm]];
            maxm[i][j] = A[i][maxi[stM]];
        }
    }
    for (int j = x; j <= N; ++j) {
        stm = stM = 1, drm = drM = 0;
        for (int i = 1; i <= M; ++i) {
            for (; stm <= drm && minm[i][j] < minm[mini[drm]][j]; --drm);
            for (; stM <= drM && maxm[i][j] > maxm[maxi[drM]][j]; --drM);
            mini[++drm] = maxi[++drM] = i;

            if (mini[stm] <= i - y) ++stm;
            if (maxi[stM] <= i - y) ++stM;

            if (i >= y) {
                int aux = maxm[maxi[stM]][j] - minm[mini[stm]][j];
                if (aux < MIN) MIN = aux, NR = 1;
                else if (aux == MIN) NR += 1;
            }
        }
    }
}

int main (void) {
    freopen (FIN, "r", stdin);
    freopen (FOU, "w", stdout);

    cit (M), cit (N), cit (T);
    for (int i = 1; i <= M; ++i)
        for (int j = 1; j <= N; ++j)
            cit (A[i][j]);
    for (int i = 1, x, y; i <= T; ++i) {
        cit (x), cit (y);
        int MIN = oo, NR = 0;
        solve (x, y, MIN, NR);
        if (x != y) solve (y, x, MIN, NR);
        printf ("%d %d\n", MIN, NR);
    }
}