Cod sursa(job #1147343)

Utilizator nimicLeoveanu Mihaita Alexandru nimic Data 19 martie 2014 19:08:23
Problema Struti Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.5 kb
#include<fstream>
#include<deque>
#include<string>
#include<stdio.h>
 
using namespace std;
 
ifstream fin( "struti.in" );
ofstream fout( "struti.out" );
 
const short int nmax = 1005;
short int n, m, sol;
int nr, act, l;
string s;
char ch;
short int a[ nmax + 1 ][ nmax + 1 ];
deque <short int> dmin, dmax;
short int hi[nmax][nmax], lo[nmax][nmax];
 
void solve(int r,int c)
{
    for(int i = 0; i<n; ++i)
    {
        dmin.clear();
        dmax.clear();

        for(int j = 0; j<m; ++j)
        {
            while(dmin.size()>0 && a[i][j]<=a[i][dmin.back()])
				dmin.pop_back();

            dmin.push_back(j);
            if(dmin.front()<=j-c)
				dmin.pop_front();

            if(j>=c-1)
				lo[i][j] = a[i][dmin.front()];
 
            while(dmax.size()>0 && a[i][j]>=a[i][dmax.back()])
				dmax.pop_back();

            dmax.push_back(j);
            if(dmax.front()<=j-c)
				dmax.pop_front();

            if(j>=c-1)
				hi[i][j] = a[i][dmax.front()];
        }
    }
 
    for(int j = c - 1; j<m; ++j)
    {
        dmin.clear();
        dmax.clear();

        for(int  i = 0; i<n; ++i)
        {
            while(dmin.size()>0 && lo[i][j]<=lo[dmin.back()][j])
				dmin.pop_back();

            dmin.push_back(i);
            if(dmin.front()<=i-r)
				dmin.pop_front();
 
            while(dmax.size()>0 && hi[i][j]>=hi[dmax.back()][j])
				dmax.pop_back();

            dmax.push_back(i);
            if(dmax.front()<=i-r)
				dmax.pop_front();
 
            if(i>=r-1)
            {
                if(hi[dmax.front()][j] - lo[dmin.front()][j]<sol)
                {
                    sol = hi[dmax.front()][j] - lo[dmin.front()][j];
                    nr = 1;
                }
                else if(hi[dmax.front()][j] - lo[dmin.front()][j]==sol)
					nr++;
            }
        }
    }
}
int main()
{
    short int t, dx, dy;
    fin>>n>>m>>t;
    for( short int i = 0; i < n; ++ i ) {
		fin>>ch;
        getline(fin,s);
		act = l = 0;
		act = ch - '0';
		for(int j = 0; j<(int)s.size(); ++j)
		{
			if(s[j]>=48 && s[j]<=57)
			{
				act = act*10 + s[j] - '0';
			}
			if(s[j]==32)
			{
				a[i][l] = act;
				act = 0;
				l++;
			}
		}
		if(l<m)
		{
			a[i][l] = act;
		}
    }
    for( short int q = 0; q < t; ++ q ) {
        fin>>dx>>dy;
        sol = 32000;
        solve( dx, dy );
        if ( dx != dy ) {
            solve( dy, dx );
        }
        fout<<sol<<' '<<nr<<'\n';
    }
    
    return 0;
}