Cod sursa(job #916635)

Utilizator vladtarniceruVlad Tarniceru vladtarniceru Data 16 martie 2013 18:57:43
Problema Struti Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.45 kb
#include <cstring>
#include <cstdio>
#include <cctype>
#include <deque>
using namespace std;

#define pb push_back
#define pf push_front
#define ppb pop_back
#define ppf pop_front
#define mp make_pair
#define all(x) x.begin(), x.end()

typedef long double lod;
typedef long long lol;
typedef pair<int, int> pii;

const int SMAX = 4096 * 1024;
char buff[SMAX];
inline int nextInt()
{
	static int I = SMAX; int ret = 0;
	if (I == SMAX) fread(buff, 1, SMAX, stdin), I = 0;
	while (!isdigit(buff[I]))
		if (++I == SMAX)
			fread(buff, 1, SMAX, stdin), I = 0;
	while (isdigit(buff[I]))
	{
		ret = ret * 10 + buff[I] - '0';
		if (++I == SMAX)
			fread(buff, 1, SMAX, stdin), I = 0;
	}
	return ret;
}

int n, m, p;
int mi[1010][1010], ma[1010][1010];
int a[1010][1010];
deque<int> Dmi, Dma;
int ljeg; pii jeg[2];

inline void dq(int x, int y)
{
	int ret = 0x3f3f3f3f, ap = 0;

	for (int j = 1; j <= m; j++)
	{
		Dmi.clear(); Dma.clear();
		for (int i = 1; i <= n; i++)
		{
			for (; Dmi.size() > 0 && a[Dmi.back()][j] > a[i][j]; Dmi.ppb());
			for (; Dma.size() > 0 && a[Dma.back()][j] < a[i][j]; Dma.ppb());
			Dmi.pb(i); Dma.pb(i);
			if (i - x == Dmi.front()) Dmi.ppf();
			if (i - x == Dma.front()) Dma.ppf();
			mi[i][j] = a[Dmi.front()][j];
			ma[i][j] = a[Dma.front()][j];
		}
	}

	for (int i = x; i <= n; i++)
	{
		Dmi.clear(); Dma.clear();
		for (int j = 1; j <= m; j++)
		{
			for (; Dmi.size() > 0 && mi[i][Dmi.back()] > mi[i][j]; Dmi.ppb());
			for (; Dma.size() > 0 && ma[i][Dma.back()] < ma[i][j]; Dma.ppb());
			Dmi.pb(j); Dma.pb(j);
			if (j - y == Dmi.front()) Dmi.ppf();
			if (j - y == Dma.front()) Dma.ppf();
			if (j >= y)
			{
				int value = ma[i][Dma.front()] - mi[i][Dmi.front()];
				if (ret > value)
					ret = value, ap = 1;
				else
				if (ret == value)
					ap++;
			}
		}
	}

	 jeg[ljeg++] = mp(ret, ap);
}

inline pii make(int x, int y)
{
	dq(x, y); dq(y, x); ljeg = 0;
	if (jeg[0].first == jeg[1].first && x != y)
		return mp(jeg[0].first, jeg[0].second + jeg[1].second);
	else
		return min(jeg[0], jeg[1]);
}

int main()
{
	freopen("struti.in", "r", stdin);
	n = nextInt(); m = nextInt(); p = nextInt();
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
			a[i][j] = nextInt();

	freopen("struti.out", "w", stdout);
	for (; p--; )
	{
		int x, y;
		x = nextInt(); y = nextInt();
		pii val;
		val = make(x, y);
		printf("%d %d\n", val.first, val.second);
	}

	return 0;
}