Cod sursa(job #3352975)

Utilizator xXoctavianXxStanescu Matei Octavian xXoctavianXx Data 3 mai 2026 02:15:12
Problema Struti Scor 40
Compilator cpp-64 Status done
Runda cerc-acs-02-05-26 Marime 2.11 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin ("struti.in");
ofstream fout("struti.out");

#define cin fin
#define cout fout

#define int long long

const int nmax = 1005;
const int inf = (1LL << 60);

int m,n,p;
int v[nmax][nmax];

pair<int,int> _solve(int dx, int dy) {
	int cols = n - dy + 1;
	vector<vector<int>> rowMin(m, vector<int>(cols));
	vector<vector<int>> rowMax(m, vector<int>(cols));

	for(int i = 0; i < m; i++) {
		deque<int> qmin, qmax;
		for(int j = 0; j < n; j++) {
			while(!qmin.empty() && v[i][qmin.back()] >= v[i][j]) qmin.pop_back();
			qmin.push_back(j);
			while(!qmax.empty() && v[i][qmax.back()] <= v[i][j]) qmax.pop_back();
			qmax.push_back(j);

			if(qmin.front() <= j - dy) qmin.pop_front();
			if(qmax.front() <= j - dy) qmax.pop_front();

			if(j >= dy - 1) {
				int pos = j - dy + 1;
				rowMin[i][pos] = v[i][qmin.front()];
				rowMax[i][pos] = v[i][qmax.front()];
			}
		}
	}

	int best = inf;
	int cnt = 0;
	for(int j = 0; j < cols; j++) {
		deque<int> qmin, qmax;
		for(int i = 0; i < m; i++) {
			while(!qmin.empty() && rowMin[qmin.back()][j] >= rowMin[i][j]) qmin.pop_back();
			qmin.push_back(i);
			while(!qmax.empty() && rowMax[qmax.back()][j] <= rowMax[i][j]) qmax.pop_back();
			qmax.push_back(i);

			if(qmin.front() <= i - dx) qmin.pop_front();
			if(qmax.front() <= i - dx) qmax.pop_front();

			if(i >= dx - 1) {
				int diff = rowMax[qmax.front()][j] - rowMin[qmin.front()][j];
				if(diff < best) {
					best = diff;
					cnt = 1;
				} else if(diff == best) {
					cnt ++;
				}
			}
		}
	}

	return {best, cnt};
}

pair<int,int> solve(int dx, int dy)
{
	if(dx != dy) {
		auto [m1, n1] = _solve(dx,dy);
		auto [m2, n2] = _solve(dy,dx);
		if(m1 == m2) {
			return make_pair(m1, n1 + n2);
		}
		return (m1 < m2) ? make_pair(m1, n1) : make_pair(m2,n2);
	}
	return _solve(dx,dy);
}

int32_t main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);

	cin >> n >> m >> p;
	for(int i = 0; i < n; i ++) {
		for(int j = 0; j < m; j++) {
			cin >> v[i][j];
		}
	}
	while(p --) {
		int dx,dy;
		cin >> dx >> dy;
		auto [minim, nr] = solve(dx, dy);
		cout << minim << ' ' << nr << '\n';
	}
	return 0;
}