Cod sursa(job #427581)

Utilizator ooctavTuchila Octavian ooctav Data 28 martie 2010 01:13:03
Problema Struti Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.77 kb
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <deque>
using namespace std;
#define SIRMAX 70000
const int INF = 1500000000;
const int NMAX = 1011;
const int MMAX = 1011;
int A[NMAX][MMAX];
int N, M, P;
int NR = 0;
int m[NMAX][MMAX];
int MX[NMAX][MMAX];
char c[SIRMAX];

void parsare()
{
	int x, j;
	for(int i = 1 ; i <= N ; i ++)
	{
		j = 0;
		x = 0;
		fgets(c,SIRMAX,stdin);
		for(int k = 0 ; c[k] && c[k] != '\n' && c[k] != EOF ; k++)
			if(c[k] == ' ')
			{
				A[i][++j] = x;
				x = 0;
			}
			else
				x = 10 * x + c[k] - '0';
		if(x)
			A[i][++j] = x;
				
	}
}

void scrie()
{
	for(int i = 1 ; i <= N ; i++)
	{
		for(int j = 1 ; j <= M ; j++)
			printf("%d ",m[i][j]);
		printf("\n");
	}
	printf("\n");
	for(int i = 1 ; i <= N ; i++)
	{
		for(int j = 1 ; j <= M ; j++)
			printf("%d ",MX[i][j]);
		printf("\n");
	}
	printf("\n");
}

int linii(int x, int y)
{
	NR = 0;
	int val = INF;
	deque<int> D;
	deque<int> d;
	
	for(int i = x ; i <= N ; i++)
	{
		for(int j = 1 ; j <= M ; j++)
		{			
			while(D.size() && MX[i][D.back()] <= MX[i][j])
					D.pop_back();
			D.push_back(j);
			if(D.front() <= j - y)
				D.pop_front();
			
			while(d.size() && m[i][d.back()] >= m[i][j])
					d.pop_back();
			d.push_back(j);
			if(d.front() <= j - y)
				d.pop_front();
				
			if(j >= y)
				if(MX[i][D.front()] - m[i][d.front()] < val)
				{
					val = MX[i][D.front()] - m[i][d.front()];
					NR = 1;
				}
				else if(MX[i][D.front()] - m[i][d.front()] == val)
					NR++;
					
		}
		D.clear();
		d.clear();
	}
	
	return val;	
}

void dq(int x, int y)
{
	deque<int> st[MMAX];
	deque<int> ST[MMAX];
	
	for(int i = 1 ; i <= N ; i++)
		for(int j = 1 ; j <= M ; j++)
		{
			while(ST[j].size() && A[ST[j].back()][j] <= A[i][j])
				ST[j].pop_back();
			ST[j].push_back(i);			
			while(ST[j].front() <= i - x)
				ST[j].pop_front();

			while(st[j].size() && A[st[j].back()][j] >= A[i][j])
				st[j].pop_back();
			st[j].push_back(i);			
			while(st[j].front() <= i - x)
				st[j].pop_front();
			
			if(i >= x)
			{
				MX[i][j] = A[ST[j].front()][j];
				m[i][j] = A[st[j].front()][j];
			}
		}
}

int main()
{
	int x, y;
	freopen("struti.in","r",stdin);
	freopen("struti.out","w",stdout);
	
	scanf("%d%d%d\n",&N,&M,&P);
	parsare();
		
	for(int k = 1 ; k <= P ; k++)
	{
		scanf("%d%d",&x,&y);
		if(x == y)
		{
			while(1);
			dq(x, y);
			printf("%d %d\n",linii(x, y), NR);
		}
		else
		{
			return 0;
			dq(x, y);
			//scrie();
			int p = linii(x, y), NR2 = NR;
			dq(y, x);
			int q = linii(y, x);
			if(p < q)
				printf("%d %d\n", p, NR2);
			else if(p > q)
				printf("%d %d\n", q, NR);
			else
				printf("%d %d\n", p, NR + NR2);
		}
	}
	
	return 0;
}