Pagini recente » Cod sursa (job #1328525) | Cod sursa (job #833092) | Cod sursa (job #1200317) | Cod sursa (job #2046206)
#include <bits/stdc++.h>
#define Nmax 1001
using namespace std;
int mat[Nmax][Nmax],n,m,k,DPmin[Nmax][Nmax],DPmax[Nmax][Nmax];
deque<pair<int,int> > Q, Q2;
pair<int,int> calcMin(int x,int y)
{
int rez = 1e9,nr = 0;
for (int i=1;i<=n;i++)
{
Q.clear();Q2.clear();
for(int j=1;j<=m;j++)
{
while (!Q.empty() && Q.back().first>=mat[i][j])
Q.pop_back();
Q.push_back({mat[i][j],j});
if(Q.front().second<=(j-x))
Q.pop_front();
while (!Q2.empty() && Q2.back().first<=mat[i][j])
Q2.pop_back();
Q2.push_back({mat[i][j],j});
if (Q2.front().second<=(j-x))
Q2.pop_front();
if (j<x)
{
DPmin[i][j] = 1e9;
DPmax[i][j] = -1e9;
}
else
{
DPmin[i][j] = Q.front().first;
DPmax[i][j] = Q2.front().first;
}
}
}
for(int j=x;j<=m;j++)
{
Q.clear();Q2.clear();
for (int i=1;i<=n;i++)
{
while (!Q.empty() && Q.back().first>=DPmin[i][j])
Q.pop_back();
Q.push_back({DPmin[i][j],i});
if(Q.front().second<=(i-y))
Q.pop_front();
while (!Q2.empty() && Q2.back().first<=DPmax[i][j])
Q2.pop_back();
Q2.push_back({DPmax[i][j],i});
if (Q2.front().second<=(i-y))
Q2.pop_front();
if(i>=y)
{
if (Q2.front().first-Q.front().first<rez)
rez = Q2.front().first-Q.front().first,nr = 1;
else if (Q2.front().first - Q.front().first==rez)
nr++;
}
}
}
return {rez,nr};
}
int main()
{
freopen("struti.in","r",stdin);
freopen("struti.out","w",stdout);
cin>>n>>m>>k;
for(int i=1;i<=n;i++)
for (int j = 1;j<=m;j++)
scanf("%d",&mat[i][j]);
int x,y;
pair<int,int> a,b;
for (int i=1;i<=k;i++)
{
cin>>x>>y;
a = calcMin(x,y);
b = calcMin(y,x);
if (a.first>b.first)
swap(a,b);
if (a.first==b.first && x!=y)
a.second += b.second;
cout<<a.first<<' '<<a.second<<'\n';
}
return 0;
}