Pagini recente » Statistici Bene Ionut (benereaper) | Monitorul de evaluare | Cod sursa (job #2029713) | Rating Bogdan Tudor-Mihai (Tudor_) | Cod sursa (job #2015306)
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>
#include <deque>
using namespace std;
const int inf = 3e4 + 5;
const int NMax = 1e3 + 5;
ifstream in("struti.in");
ofstream out("struti.out");
#define ll long long
#define ull unsigned long long
#define pb push_back
using zint = short;
zint N,M,P;
zint a[NMax][NMax];
void solve(zint,zint,zint&,int&);
int main() {
in>>N>>M>>P;
for (zint i=1;i <= N;++i) {
for (zint j=1;j <= M;++j) {
in>>a[i][j];
}
}
while (P--) {
zint dx,dy;
in>>dx>>dy;
zint min1,min2;
int nrMin1,nrMin2;
solve(dx,dy,min1,nrMin1);
//cout<<min1<<' '<<nrMin1<<'\n';
if (dx != dy) {
solve(dy,dx,min2,nrMin2);
//cout<<min2<<' '<<nrMin2<<'\n';
if (min1 == min2) {
nrMin1 += nrMin2;
}
else if (min1 > min2) {
min1 = min2;
nrMin1 = nrMin2;
}
}
//cout<<'\n';
out<<min1<<' '<<nrMin1<<'\n';
}
in.close();out.close();
return 0;
}
void solve(zint dx,zint dy,zint& mn,int& nrMin) {
deque<zint> rowMn[NMax],rowMx[NMax];
mn = inf, nrMin = 0;
for (int j=1;j <= M;++j) {
for (int i=1;i <= N;++i) {
while (rowMn[i].size() && a[i][rowMn[i].back()] >= a[i][j]) {
rowMn[i].pop_back();
}
rowMn[i].push_back(j);
if (rowMn[i].front() == j-dy) {
rowMn[i].pop_front();
}
while (rowMx[i].size() && a[i][rowMx[i].back()] <= a[i][j]) {
rowMx[i].pop_back();
}
rowMx[i].push_back(j);
if (rowMx[i].front() == j-dy) {
rowMx[i].pop_front();
}
//cout<<i<<' '<<rowMn[i].front()<<' '<<rowMx[i].front()<<'\n';
}
//cout<<'\n';
if (j >= dy) {
deque<zint> colMn,colMx;
for (int i=1;i <= N;++i) {
short idx;
while (colMn.size() && a[idx = colMn.back()][rowMn[idx].front()] >= a[i][rowMn[i].front()]) {
colMn.pop_back();
}
colMn.push_back(i);
if (colMn.front() == i-dx) {
colMn.pop_front();
}
while (colMx.size() && a[idx = colMx.back()][rowMx[idx].front()] <= a[i][rowMx[i].front()]) {
colMx.pop_back();
}
colMx.push_back(i);
if (colMx.front() == i-dx) {
colMx.pop_front();
}
//cout<<i<<' '<<colMn.front()<<' '<<colMx.front()<<"\n\n\n";
if (i >= dx) {
short idxMx = colMx.front(),
idxMn = colMn.front();
short val = a[idxMx][rowMx[idxMx].front()] -
a[idxMn][rowMn[idxMn].front()];
//cout<<val<<"\n\n\n";
if (mn > val) {
mn = val;
nrMin = 1;
}
else if (mn == val) {
++nrMin;
}
}
}
}
}
}