Cod sursa(job #1993790)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 23 iunie 2017 19:15:34
Problema Struti Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.5 kb
#include <fstream>

using namespace std;

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

const int nmax = 1000 + 5;
const int inf = 1 << 30;

int n, m;
int v[nmax + 1][nmax + 1];

pair<int, int> mx[nmax + 1], mn[nmax + 1], mncol[nmax + 1][nmax + 1], mxcol[nmax + 1][nmax + 1];

void baga_minim (pair<int, int> d[nmax + 1], int val, int pos, int lg) {
    while (d[ 0 ].first <= d[ 0 ].second && d[ d[ 0 ].second ].first >= val) {
        -- d[ 0 ].second;
    }
    d[ ++ d[ 0 ].second ] = make_pair(val, pos);

    if (d[ d[ 0 ].first ].second <= pos - lg) {
        ++ d[ 0 ].first;
    }
}

void baga_maxim (pair<int, int> d[nmax + 1], int val, int pos, int lg) {
    while (d[ 0 ].first <= d[ 0 ].second && d[ d[ 0 ].second ].first <= val) {
        -- d[ 0 ].second;
    }
    d[ ++ d[ 0 ].second ] = make_pair(val, pos);

    if (d[ d[ 0 ].first ].second <= pos - lg) {
        ++ d[ 0 ].first;
    }
}

pair<int, int> solve (int x, int y) {
    for (int i = 1; i <= m; ++ i) {
        mncol[ i ][ 0 ] = make_pair(1, 0);
        mxcol[ i ][ 0 ] = make_pair(1, 0);
    }

    int sol, cate;
    sol = inf; cate = 0;
    for (int i = 1; i <= n; ++ i) {
        for (int j = 1; j <= m; ++ j) {
            baga_minim(mncol[ j ], v[ i ][ j ], i, x);
            baga_maxim(mxcol[ j ], v[ i ][ j ], i, x);
        }

        mn[ 0 ] = make_pair(1, 0);
        mx[ 0 ] = make_pair(1, 0);

        for (int j = 1; j <= m; ++ j) {
            baga_minim(mn, mncol[ j ][ mncol[ j ][ 0 ].first ].first, j, y);
            baga_maxim(mx, mxcol[ j ][ mxcol[ j ][ 0 ].first ].first, j, y);

            if (x <= i && y <= j) {
                int dif = mx[ mx[ 0 ].first ].first - mn[ mn[ 0 ].first ].first;
                if (dif < sol) {
                    sol = dif; cate = 0;
                }
                cate += (dif == sol);
            }
        }
    }

    return make_pair(sol, cate);
}

int main() {
    int q;
    fin >> n >> m >> q;
    for (int i = 1; i <= n; ++ i) {
        for (int j = 1; j <= m; ++ j) {
            fin >> v[ i ][ j ];
        }
    }

    while (q --) {
        int x, y;
        fin >> x >> y;

        pair<int, int> ans1 = solve(x, y);
        if (x != y) {
            pair<int, int> ans2 = solve(y, x);

            if (ans1.first == ans2.first) {
                ans1.second += ans2.second;
            } else if (ans1.first > ans2.first) {
                ans1 = ans2;
            }
        }

        fout << ans1.first << " " << ans1.second << "\n";
    }

    fin.close();
    fout.close();
    return 0;
}