Cod sursa(job #1993781)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 23 iunie 2017 18:59:50
Problema Struti Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.18 kb
#include <fstream>
#include <deque>

using namespace std;

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

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

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

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

void baga_minim (deque<pair<int, int>> &d, int val, int pos, int lg) {
    while (!d.empty() && d.back().first >= val) {
        d.pop_back();
    }
    d.push_back(make_pair(val, pos));

    if (d.front().second <= pos - lg) {
        d.pop_front();
    }
}

void baga_maxim (deque<pair<int, int>> &d, int val, int pos, int lg) {
    while (!d.empty() && d.back().first <= val) {
        d.pop_back();
    }
    d.push_back(make_pair(val, pos));

    if (d.front().second <= pos - lg) {
        d.pop_front();
    }
}

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

    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.clear(); mx.clear();
        for (int j = 1; j <= m; ++ j) {
            baga_minim(mn, mncol[ j ].front().first, j, y);
            baga_maxim(mx, mxcol[ j ].front().first, j, y);

            if (x <= i && y <= j) {
                int dif = mx.front().first - mn.front().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;
            }
        }

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

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