Cod sursa(job #1082731)

Utilizator dan.ghitaDan Ghita dan.ghita Data 14 ianuarie 2014 21:34:39
Problema Struti Scor 0
Compilator cpp Status done
Runda Teme Pregatire ACM Unibuc 2013 Marime 2.25 kb
#include<iostream>
#include<fstream>
using namespace std;
ifstream f("struti.in");
ofstream g("struti.out");

int n, i, j, dx, dy, nrs, sol, a[1003][1003], b[1003][1003][2], m, p;

struct struti
{
    int x, y;
};
struti q[1003][2];

void src(int X, int Y)
{
    int s1, s2, f1, f2, i, j;
    for (i = 1; i <= n; i ++)
    {
        s1 = s2 = 1, f1 = f2 = 0;

        for (j = 1; j <= m; j ++)
        {
            if (s1 < f1 && j - q[s1][0].y + 1 > X)
                s1 ++;
            while (s1 <= f1 && a[i][j] <= q[f1][0].x)
                f1 --;
            f1 ++;
            q[f1][0].x = a[i][j], q[f1][0].y = j;

            if (s2 < f2 && j - q[s2][1].y + 1 > X)
                s2 ++;
            while (s2 <= f2 && a[i][j] >= q[f2][1].x)
                f2 --;
            f2 ++;
            q[f2][1].x = a[i][j], q[f2][1].y = j;


            if (j >= X)
            {
                b[i][j - X + 1][0] = q[s1][0].x;
                b[i][j - X + 1][1] = q[s2][1].x;
            }
        }
    }
    for (j = 1; j <= m - X + 1; j ++)
    {
        s1 = s2 = 1, f1 = f2 = 0;

        for (i = 1; i <= n; i ++)
        {
            if (s1 < f1 && i - q[s1][0].y + 1 > Y)
                s1 ++;
            while (s1 <= f1 && b[i][j][0] <= q[f1][0].x)
                f1 --;
            f1 ++;
            q[f1][0].x = b[i][j][0], q[f1][0].y = i;

            if (s2 < f2 && i - q[s2][1].y + 1 > Y)
                s2 ++;
            while (s2 <= f2 && b[i][j][1] >= q[f2][1].x)
                f2 --;
            f2 ++;
            q[f2][1].x = b[i][j][1], q[f2][1].y = i;

            if (i >= Y)
            {
                if (q[s2][1].x - q[s1][0].x < sol)
                {
                    sol = q[s2][1].x - q[s1][0].x;
                    nrs = 0;
                }
                if (q[s2][1].x - q[s1][0].x == sol)
                    nrs ++;
            }
        }
    }
}

int main()
{
    f>>n>>m>>p;
    for (i = 1; i <= n; i ++)
        for (j = 1; j <= m; j ++)
            f>>a[i][j];

    while (p --)
    {
        f>>dx>>dy;
        sol = 1<<30;
        src(dx, dy);
        if (dx != dy)
            src(dy, dx);

        g<<sol<<nrs<<'\n';
    }

    return 0;
}