Pagini recente » Cod sursa (job #883743) | Monitorul de evaluare | Cod sursa (job #2707948) | Cod sursa (job #2857748) | Cod sursa (job #2913821)
#include <iostream>
#include <fstream>
#include <deque>
#define pii pair <int, int>
using namespace std;
ifstream fin("struti.in");
ofstream fout("struti.out");
const int N = 1000, inf = 1e9;
int n, m, mat[N + 1][N + 1], auxMin[N + 1][N + 1], auxMax[N + 1][N + 1];
pii solve(int lin, int col){
deque <int> dq;
for(int j = 1; j <= m; j++){
while(!dq.empty())
dq.pop_back();
for(int i = 1; i <= n; i++){
while(!dq.empty() && mat[dq.back()][j] > mat[i][j])
dq.pop_back();
dq.push_back(i);
if(i >= lin){
if(dq.front() <= i - lin)
dq.pop_front();
auxMin[i - lin + 1][j] = mat[dq.front()][j];
}
}
}
for(int j = 1; j <= m; j++){
while(!dq.empty())
dq.pop_back();
for(int i = 1; i <= n; i++){
while(!dq.empty() && mat[dq.back()][j] < mat[i][j])
dq.pop_back();
dq.push_back(i);
if(i >= lin){
if(dq.front() <= i - lin)
dq.pop_front();
auxMax[i - lin + 1][j] = mat[dq.front()][j];
}
}
}
deque <int> dqMin, dqMax;
int ans = inf, f = 0;
for(int i = 1; i <= n - lin + 1; i++){
while(!dqMin.empty())
dqMin.pop_back();
while(!dqMax.empty())
dqMax.pop_back();
for(int j = 1; j <= m; j++){
while(!dqMin.empty() && auxMin[i][dqMin.back()] > auxMin[i][j])
dqMin.pop_back();
dqMin.push_back(j);
while(!dqMax.empty() && auxMax[i][dqMax.back()] < auxMax[i][j])
dqMax.pop_back();
dqMax.push_back(j);
if(j >= col){
if(dqMin.front() <= j - col)
dqMin.pop_front();
if(dqMax.front() <= j - col)
dqMax.pop_front();
if(auxMax[i][dqMax.front()] - auxMin[i][dqMin.front()] < ans)
ans = auxMax[i][dqMax.front()] - auxMin[i][dqMin.front()], f = 1;
else if(auxMax[i][dqMax.front()] - auxMin[i][dqMin.front()] == ans)
f++;
}
}
}
return {ans, f};
}
int main(){
int q;
fin >> n >> m >> q;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
fin >> mat[i][j];
while(q--){
int lin, col;
fin >> lin >> col;
pii ans1 = solve(lin, col);
pii ans2 = solve(col, lin);
if(lin != col){
if(ans1.first < ans2.first)
fout << ans1.first << ' ' << ans1.second << '\n';
else if(ans1.first > ans2.first)
fout << ans2.first << ' ' << ans2.second << '\n';
else
fout << ans1.first << ' ' << ans1.second + ans2.second << '\n';
}else
fout << ans1.first << ' ' << ans1.second << '\n';
}
return 0;
}