Pagini recente » Cod sursa (job #2149633) | Cod sursa (job #2825073) | Cod sursa (job #2452754) | Cod sursa (job #963289) | Cod sursa (job #2807513)
#include <fstream>
#include <deque>
#include <iomanip>
using namespace std;
const short int N = 1000;
const short int INF = 1e4;
short int nl, nc, a[N][N], mini[N][N], maxi[N][N];
ifstream in("struti.in");
ofstream out("struti.out");
void coloana_mini(short int c, short int dy)
{
deque <int> d;
for (short int i = 0; i < nl; i++)
{
if (!d.empty() && d.front() == i - dy)
{
d.pop_front();
}
while (!d.empty() && a[d.back()][c] >= a[i][c])
{
d.pop_back();
}
d.push_back(i);
mini[i][c] = a[d.front()][c];
}
}
void calcul_mini(short int dy)
{
for (short int j = 0; j < nc; j++)
{
coloana_mini(j, dy);
}
}
void coloana_maxi(short int c, short int dy)
{
deque <int> d;
for (short int i = 0; i < nl; i++)
{
if (!d.empty() && d.front() == i - dy)
{
d.pop_front();
}
while (!d.empty() && a[d.back()][c] <= a[i][c])
{
d.pop_back();
}
d.push_back(i);
maxi[i][c] = a[d.front()][c];
}
}
void calcul_maxi(short int dy)
{
for (short int j = 0; j < nc; j++)
{
coloana_maxi(j, dy);
}
}
void diferenta_min(short int dx, short int dy, short int &dif_min, int &nr)
{
calcul_mini(dy);
calcul_maxi(dy);
deque <int> dmin, dmax;
for (short int i = dy - 1; i < nl; i++)
{
dmin.clear();
dmax.clear();
for (short int j = 0; j < nc; j++)
{
///actualizez in deque-ul de minime
if (!dmin.empty() && dmin.front() == j - dx)
{
dmin.pop_front();
}
while (!dmin.empty() && mini[i][dmin.back()] >= mini[i][j])
{
dmin.pop_back();
}
dmin.push_back(j);
///actualizez in deque-ul de maxime
if (!dmax.empty() && dmax.front() == j - dx)
{
dmax.pop_front();
}
while (!dmax.empty() && maxi[i][dmax.back()] <= maxi[i][j])
{
dmax.pop_back();
}
dmax.push_back(j);
if (j < dx - 1) continue;
short int rez_actual = maxi[i][dmax.front()] - mini[i][dmin.front()];
if (rez_actual < dif_min)
{
dif_min = rez_actual;
nr = 1;
}
else if (rez_actual == dif_min)
{
nr++;
}
}
}
}
void calcul(short int dx, short int dy)
{
short int difmin = INF;
int nr;
diferenta_min(dx, dy, difmin, nr);
if (dx != dy)
{
diferenta_min(dy, dx, difmin, nr);
}
out << difmin << " " << nr << "\n";
}
int main()
{
short int p;
in >> nl >> nc >> p;
for (short int i = 0; i < nl; i++)
{
for (short int j = 0; j < nc; j++)
{
in >> a[i][j];
}
}
for (short int i = 0; i < p; i++)
{
short int dx, dy;
in >> dx >> dy;
calcul(dx, dy);
}
in.close();
out.close();
return 0;
}