(2012-05-03 17:39:41)
SOJ3636:http://cstest.scu.edu.cn/soj/problem.action?id=3636
这道题就是纯粹地利用双端对列。注意:先横向处理再纵向处理。
代码:
#include<iostream>
#include<cstring>
#include<deque>
using namespace std;
int s[1005][1005];
int Min[1005][1005];
int Max[1005][1005];
int result[1005][1005];
struct node
{
int position;
int number;
};
int main()
{
int a,b,n;
int i,j;
while(scanf("%d%d%d",&a,&b,&n)==3)
{
int fk=0xffffff;
for(i=1;i<=a;i++)
for(j=1;j<=b;j++)
scanf("%d",&s[i][j]);
node temp;
deque<node>ye;
for(i=1;i<=a;i++)
{
for(j=1;j<n;j++)
{
while(!ye.empty() && ye.back().number>=s[i][j])
ye.pop_back();
temp.position=j;
temp.number=s[i][j];
ye.push_back(temp);
}
for(j=n;j<=b;j++)
{
while(!ye.empty() && ye.back().number>=s[i][j])
ye.pop_back();
temp.position=j;
temp.number=s[i][j];
ye.push_back(temp);
while(ye.front().position<j-n+1)
ye.pop_front();
Min[i][j]=ye.front().number;
}
ye.clear();
}
for(j=n;j<=b;j++)
{
for(i=1;i<n;i++)
{
while(!ye.empty() && ye.back().number>=Min[i][j])
ye.pop_back();
temp.position=i;
temp.number=Min[i][j];
ye.push_back(temp);
}
for(i=n;i<=a;i++)
{
while(!ye.empty() && ye.back().number>=Min[i][j])
ye.pop_back();
temp.position=i;
temp.number=Min[i][j];
ye.push_back(temp);
while(ye.front().position<i-n+1)
ye.pop_front();
result[i][j]=ye.front().number;
}
ye.clear();
}
///
for(i=1;i<=a;i++)
{
for(j=1;j<n;j++)
{
while(!ye.empty() && ye.back().number<=s[i][j])
ye.pop_back();
temp.position=j;
temp.number=s[i][j];
ye.push_back(temp);
}
for(j=n;j<=b;j++)
{
while(!ye.empty() && ye.back().number<=s[i][j])
ye.pop_back();
temp.position=j;
temp.number=s[i][j];
ye.push_back(temp);
while(ye.front().position<j-n+1)
ye.pop_front();
Max[i][j]=ye.front().number;
}
ye.clear();
}
for(j=n;j<=b;j++)
{
for(i=1;i<n;i++)
{
while(!ye.empty() && ye.back().number<=Max[i][j])
ye.pop_back();
temp.position=i;
temp.number=Max[i][j];
ye.push_back(temp);
}
for(i=n;i<=a;i++)
{
while(!ye.empty() && ye.back().number<=Max[i][j])
ye.pop_back();
temp.position=i;
temp.number=Max[i][j];
ye.push_back(temp);
while(ye.front().position<i-n+1)
ye.pop_front();
result[i][j]=ye.front().number-result[i][j];
if(result[i][j]<fk)
fk=result[i][j];
}
ye.clear();
}
printf("%d\n",fk);
}
return 0;
}