Cod sursa(job #3312017)

Utilizator mihai.25Calin Mihai mihai.25 Data 25 septembrie 2025 15:49:26
Problema Struti Scor 100
Compilator cpp-64 Status done
Runda Teme Pregatire ACM Unibuc 2013 Marime 2.76 kb
#include <fstream>

#include <vector>

#include <deque>

using namespace std;

int n, m, p;

vector<vector<int>> mat (1001, vector<int> (1001));

pair<int, long long> rezolvare (int h, int w) {

	vector<vector<int>> rand_min (n + 1, vector<int> (m - w + 2));

	vector<vector<int>> rand_max (n + 1, vector<int> (m - w + 2));

	for (int i = 1; i <= n; ++i) {

		deque<int> dqmin, dqmax;

		for (int j = 1; j <= m; ++j) {

			while (!dqmin.empty() && dqmin.front() <= j - w)
				dqmin.pop_front();
			
			while (!dqmax.empty() && dqmax.front() <= j - w)
				dqmax.pop_front();
			
			while (!dqmin.empty() && mat[i][dqmin.back()] >= mat[i][j])
				dqmin.pop_back();
			
			dqmin.push_back(j);

			while (!dqmax.empty() && mat[i][dqmax.back()] <= mat[i][j])
				dqmax.pop_back();
			
			dqmax.push_back(j);

			if (j >= w) {

				rand_min[i][j - w + 1] = mat[i][dqmin.front()];

				rand_max[i][j - w + 1] = mat[i][dqmax.front()];
			}
		}
	}

	int R = n - h + 1, C = m - w + 1;

	vector<vector<int>> submat_min (R + 1, vector<int> (C + 1));

	vector<vector<int>> submat_max (R + 1, vector<int> (C + 1));

	for (int j = 1; j <= C; ++j) {

		deque<int> dqmin, dqmax;

		for (int i = 1; i <= n; ++i) {

			while (!dqmin.empty() && dqmin.front() <= i - h)
				dqmin.pop_front();
			
			while (!dqmax.empty() && dqmax.front() <= i - h)
				dqmax.pop_front();
			
			while (!dqmin.empty() && rand_min[dqmin.back()][j] >= rand_min[i][j])
				dqmin.pop_back();
			
			dqmin.push_back(i);
			
			while (!dqmax.empty() && rand_max[dqmax.back()][j] <= rand_max[i][j])
				dqmax.pop_back();
			
			dqmax.push_back(i);
			
			if (i >= h) {

				submat_min[i - h + 1][j] = rand_min[dqmin.front()][j];

				submat_max[i - h + 1][j] = rand_max[dqmax.front()][j];
			}
		}
	}

	int dif_min = 1e9;

	long long cnt = 0;

	for (int i = 1; i <= R; ++i) {

		for (int j = 1; j <= C; ++j) {

			int dif = submat_max[i][j] - submat_min[i][j];

			if (dif < dif_min) {

				dif_min = dif;

				cnt = 1;
			}
			else {
				
				if (dif == dif_min)
					cnt++;
			}
		}
	}

	return {dif_min, cnt};
}

int main () {

	ifstream fin ("struti.in");

	ofstream fout ("struti.out");

	fin >> n >> m >> p;

	for (int i = 1; i <= n; ++i)
		for (int j = 1; j <= m; ++j)
			fin >> mat[i][j];

	for (int i = 1; i <= p; ++i) {

		int dx, dy;

		fin >> dx >> dy;

		pair<int, long long> rez = rezolvare (dx, dy);

		if (dx != dy) {

			pair<int, long long> x = rezolvare (dy, dx);

			if (x.first < rez.first) {

				rez.first = x.first;

				rez.second = x.second;
			}
			else {

				if (x.first == rez.first)
					rez.second += x.second;
			}
		}

		fout << rez.first << ' ' << rez.second << '\n';
	}

	return 0;
}