Cod sursa(job #1085911)

Utilizator laurionLaurentiu Ion laurion Data 17 ianuarie 2014 15:31:44
Problema Struti Scor 100
Compilator cpp Status done
Runda Teme Pregatire ACM Unibuc 2013 Marime 2.64 kb
#define nume "struti"

#ifndef INFOARENA
#define fisier "../algorithm solutions/" nume
#define DBG
#else
#define fisier nume
#endif

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
#include <cassert>
#include <cstring>
#include <map>
#ifdef INFOARENA
#include <tr1/unordered_set>
#include <tr1/unordered_map>
using namespace std::tr1;
#else
#include <unordered_set>
#include <unordered_map>
#endif

using namespace std;

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

#ifdef DBG
#define fout cout
#endif

const int MAX_N = 1000 + 1;
const int oo = 0x3f3f3f3f;

int n,m;
int mat[MAX_N][MAX_N];
int min_i[MAX_N], max_i[MAX_N];
int min_mat[MAX_N][MAX_N], max_mat[MAX_N][MAX_N];
int left_min, left_max, right_min, right_max, poz;

int minim, nr;
inline void adjustMinMax(int i, int dx)
{
    min_i[++right_min] = max_i[++right_max] = i;
    
    if(min_i[left_min] <= i - dx)
        ++left_min;
    if(max_i[left_max] <= i - dx)
        ++left_max;
}
void solve (int dx, int dy) {
    for (int i = 1; i <= n; i ++) {
        left_min = left_max = 1;
        right_min = right_max = 0;
        for (int j = 1; j <= m; j ++) {
            while(left_min <= right_min && mat[i][j] < mat[i][min_i[right_min]])
                --right_min;
            while(left_max <= right_max && mat[i][j] > mat[i][max_i[right_max]])
                --right_max;
            
            adjustMinMax(j, dx);
            
            min_mat[i][j] = mat[i][min_i[left_min]];
            max_mat[i][j] = mat[i][max_i[left_max]];
        }
    }
    for (int j = dx; j <= m; j ++) {
        left_min = left_max = 1;
        right_min = right_max = 0;
        for (int i = 1; i <= n; i ++) {
            while(left_min <= right_min && min_mat[i][j] < min_mat[min_i[right_min]][j])
                --right_min;
            while(left_max <= right_max && max_mat[i][j] > max_mat[max_i[right_max]][j])
                --right_max;
            
            adjustMinMax(i, dy);
            
            if(i >= dy) {
                int minmax = max_mat[max_i[left_max]][j] - min_mat[min_i[left_min]][j];
                if (minmax < minim){
                    nr = 1;
                    minim = minmax;
                }
                else if (minmax == minim)
                    nr ++;
            }
        }
    }
}

int main () {
    int p;
    fin>>n>>m>>p;

    for (int i = 1; i <= n; i ++)
        for (int j = 1; j <= m; j ++)
            fin>>mat[i][j];
    int dx, dy;
    while(p--) {
        fin>>dx>>dy;
        minim = oo, nr = 0;
        solve (dx, dy);
        if (dx - dy) solve (dy, dx);
        fout<<minim<<' '<<nr<<'\n';
    }
    
    return 0;
}