Pagini recente » Cod sursa (job #2950146) | Cod sursa (job #1989895) | Cod sursa (job #572237) | Cod sursa (job #3247931) | Cod sursa (job #1082227)
#include <cstdio>
#include <cctype>
#include <deque>
using namespace std;
const int Nmax = 1024;
const int Inf = 1 << 30;
const int BuffSize = 8192;
int mat[Nmax][Nmax], a[Nmax][Nmax], b[Nmax][Nmax];
deque<int> dq_min, dq_max;
int n, m, t, dx, dy, sol, nr_sol;
int pos = BuffSize;
char buff[BuffSize];
inline char getChar(FILE *f) {
if (pos == BuffSize) {
fread(buff, 1, BuffSize, f);
pos = 0;
}
return buff[pos++];
}
inline int read(FILE *f) {
int result = 0;
char c;
do {
c = getChar(f);
} while (!isdigit(c));
do {
result = 10 * result + c - '0';
c = getChar(f);
} while (isdigit(c));
return result;
}
void solve() {
int i, k, lin, col, max_val, min_val;
for (lin = 1; lin <= n; lin++) {
k = dy;
dq_min.clear();
dq_max.clear();
for (i = 1; i <= m; i++) {
while (!dq_min.empty() and mat[lin][i] <= mat[lin][dq_min.back()])
dq_min.pop_back();
while (!dq_max.empty() and mat[lin][i] >= mat[lin][dq_max.back()])
dq_max.pop_back();
dq_min.push_back(i);
dq_max.push_back(i);
if (dq_min.front() == i - k)
dq_min.pop_front();
if (dq_max.front() == i - k)
dq_max.pop_front();
if (i >= k) {
a[lin][i] = mat[lin][dq_min.front()];
b[lin][i] = mat[lin][dq_max.front()];
}
}
}
for (col = dy; col <= m; col++) {
k = dx;
dq_min.clear();
dq_max.clear();
for (i = 1; i <= n; i++) {
while (!dq_min.empty() and a[i][col] <= a[dq_min.back()][col])
dq_min.pop_back();
while (!dq_max.empty() and b[i][col] >= b[dq_max.back()][col])
dq_max.pop_back();
dq_min.push_back(i);
dq_max.push_back(i);
if (dq_min.front() == i - k)
dq_min.pop_front();
if (dq_max.front() == i - k)
dq_max.pop_front();
if (i >= k) {
min_val = a[dq_min.front()][col];
max_val = b[dq_max.front()][col];
}
if (i >= dx) {
if (max_val - min_val < sol) {
sol = max_val - min_val;
nr_sol = 1;
} else if (max_val - min_val == sol)
nr_sol++;
}
}
}
}
int main() {
FILE *f = fopen("struti.in", "r");
FILE *g = fopen("struti.out", "w");
int i, j, aux;
n = read(f);
m = read(f);
t = read(f);
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++)
mat[i][j] = read(f);
while (t--) {
dx = read(f);
dy = read(f);
sol = Inf, nr_sol = 0;
solve();
if (dx != dy) {
aux = dx;
dx = dy;
dy = aux;
solve();
}
fprintf(g, "%d %d\n", sol, nr_sol);
}
fclose(f);
fclose(g);
return 0;
}