记录编号 151714 评测结果 AAAAAAAAAA
题目名称 [HAOI 2007]理想的正方形 最终得分 100
用户昵称 GravatarHouJikan 是否通过 通过
代码语言 C++ 运行时间 1.143 s
提交时间 2015-03-09 19:57:53 内存使用 10.34 MiB
显示代码纯文本
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <list>
#include <vector>
#include <ctime>
#include <functional>
#define pritnf printf
#define scafn scanf
#define sacnf scanf
#define For(i,j,k) for(int i=(j);i<=(k);(i)++)
#define Clear(a) memset(a,0,sizeof(a))
using namespace std;
typedef unsigned int Uint;
const int INF=0x3fffffff;
///==============struct declaration==============

///==============var declaration=================
const int MAXN=1050;
int row,col,k;
int minv[MAXN][MAXN],maxv[MAXN][MAXN],val[MAXN][MAXN];
deque <int> BQ,SQ;
///==============function declaration============

///==============main code=======================
int main()
{

   freopen("square.in","r",stdin);
   freopen("square.out","w",stdout);

   scanf("%d%d%d",&row,&col,&k);
   for(int i=1;i<=row;i++)
      for(int j=1;j<=col;j++)
         scanf("%d",&val[i][j]);
   for(int i=1;i<=row;i++){
      SQ.clear();BQ.clear();
      for(int j=1;j<=col;j++){
         while (!SQ.empty()&&val[i][SQ.back()]>=val[i][j])
            SQ.pop_back();
         SQ.push_back(j);
         while (!BQ.empty()&&val[i][BQ.back()]<=val[i][j])
            BQ.pop_back();
         BQ.push_back(j);
         while (BQ.front()<=j-k) BQ.pop_front();
         while (SQ.front()<=j-k) SQ.pop_front();
         maxv[i][j]=val[i][BQ.front()];minv[i][j]=val[i][SQ.front()];
      }
   }
   int ans=INF;
   for(int c=k;c<=col;c++){
      BQ.clear();SQ.clear();
      for(int r=1;r<=row;r++){
         while (!SQ.empty()&&minv[SQ.back()][c]>=minv[r][c])  SQ.pop_back();
         SQ.push_back(r);
         while (!BQ.empty()&&maxv[BQ.back()][c]<=maxv[r][c])  BQ.pop_back();
         BQ.push_back(r);
         while (BQ.front()<=r-k) BQ.pop_front();
         while (SQ.front()<=r-k) SQ.pop_front();
         if (r>=k)
         ans=min(ans,maxv[BQ.front()][c]-minv[SQ.front()][c]);
      }
   }
   /*for(int i=1;i<=row;i++)
      for(int j=1;j<=col;j++)
         if (j==col)
            printf("%d\n",maxv[i][j]);
         else
            printf("%d ",maxv[i][j]);*/
   printf("%d\n",ans);
   return 0;
}
///================fuction code====================