Pagini recente » Cod sursa (job #1495027) | Cod sursa (job #1597601) | Cod sursa (job #2623051) | Cod sursa (job #377078) | Cod sursa (job #1395980)
#include <cstdio>
FILE* in=fopen("struti.in","r");
FILE* out=fopen("struti.out","w");
int l,c,q;
const int Q=1007,INF=2000000000;
int v[Q][Q];
int rez,nr;
struct deque
{
int val[Q],st,dr;
deque()
{
st=1;
dr=0;
}
void clear()
{
st=1;
dr=0;
}
bool empty()
{
return st>dr;
}
int back()
{
return val[dr];
}
void pop_back()
{
dr--;
}
int front()
{
return val[st];
}
void pop_front()
{
st++;
}
void push_back(int x)
{
dr++;
val[dr]=x;
}
} min[Q],max[Q], f,t;;
int trie(int x, int y)
{
for(int i=1; i<=l || i<=c; i++)
{
min[i].clear();
max[i].clear();
}
for(int i=1; i<=l; i++)
{
for(int j=1; j<y; j++)
{
while(!min[i].empty() && v[i][min[i].back()]>v[i][j])
min[i].pop_back();
min[i].push_back(j);
while(!max[i].empty() && v[i][max[i].back()]<v[i][j])
max[i].pop_back();
max[i].push_back(j);
}
}
for(int j=y; j<=c; j++)
{
for(int i=1; i<=l; i++)
{
while(min[i].front()<=j-y)
min[i].pop_front();
while(!min[i].empty() && v[i][min[i].back()]>v[i][j])
min[i].pop_back();
min[i].push_back(j);
while(max[i].front()<=j-y)
max[i].pop_front();
while(!max[i].empty() && v[i][max[i].back()]<v[i][j])
max[i].pop_back();
max[i].push_back(j);
}
t.clear();
f.clear();
for(int i=1; i<x; i++)
{
while( !t.empty() && v[t.back()][min[t.back()].front()] > v[i][ min[i].front()])
t.pop_back();
t.push_back(i);
while( !f.empty() && v[f.back()][max[f.back()].front()] < v[i][max[i].front()] )
f.pop_back();
f.push_back(i);
}
for(int i=x; i<=l; i++)
{
while( i-t.front()>=x)
t.pop_front();
while(i-f.front()>=x)
f.pop_front();
while( !t.empty() && v[t.back()][min[t.back()].front()] > v[i][ min[i].front()])
t.pop_back();
t.push_back(i);
while( !f.empty() && v[f.back()][max[f.back()].front()] < v[i][max[i].front()] )
f.pop_back();
f.push_back(i);
if(v[f.front()][max[f.front()].front() ] - v[t.front()][min[t.front()].front()] == rez)
nr++;
if(v[f.front()][max[f.front()].front() ] - v[t.front()][min[t.front()].front()] < rez)
{
nr=1;
rez=v[f.front()][max[f.front()].front() ] - v[t.front()][min[t.front()].front()];
}
}
}
}
int main()
{
fscanf(in,"%d%d%d",&l,&c,&q);
for(int i=1; i<=l; i++)
{
for(int j=1; j<=c; j++)
{
fscanf(in,"%d",&v[i][j]);
}
}
int x,y;
for(int i=1; i<=q; i++)
{
fscanf(in,"%d%d",&x,&y);
rez=INF;
nr=0;
trie(x,y);
if(x!=y)
trie(y,x);
fprintf(out,"%d %d\n",rez,nr);
}
return 0;
}