)逼着自己写DP
题意:
给定一个带有数字的矩阵,找出一个大小为n*n的矩阵,这个矩阵中最大值减最小值最小。
思路:
先处理出每一行每个格子到前面n个格子中的最大值和最小值。然后对每一列求出长度为n的前面算出来的最大值的最大值,前面算出来的最小值的最小值。如果直接做是n的三次方,但是用单调队列优化后就是n方的。
#include <algorithm>
#include <iterator>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <iomanip>
#include <bitset>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <stack>
#include <cmath>
#include <queue>
#include <list>
#include <map>
#include <set>
#include <cassert> using namespace std;
#define lson (l , mid , rt << 1)
#define rson (mid + 1 , r , rt << 1 | 1)
#define debug(x) cerr << #x << " = " << x << "\n";
#define pb push_back
#define pq priority_queue typedef long long ll;
typedef unsigned long long ull;
//typedef __int128 bll;
typedef pair<ll ,ll > pll;
typedef pair<int ,int > pii;
typedef pair<int,pii> p3; //priority_queue<int> q;//这是一个大根堆q
//priority_queue<int,vector<int>,greater<int> >q;//这是一个小根堆q
#define fi first
#define se second
//#define endl '\n' #define OKC ios::sync_with_stdio(false);cin.tie(0)
#define FT(A,B,C) for(int A=B;A <= C;++A) //用来压行
#define REP(i , j , k) for(int i = j ; i < k ; ++i)
#define max3(a,b,c) max(max(a,b), c);
#define min3(a,b,c) min(min(a,b), c);
//priority_queue<int ,vector<int>, greater<int> >que; const ll mos = 0x7FFFFFFF; //
const ll nmos = 0x80000000; //-2147483648
const int inf = 0x3f3f3f3f;
const ll inff = 0x3f3f3f3f3f3f3f3f; //
const int mod = 1e8+;
const double esp = 1e-;
const double PI=acos(-1.0);
const double PHI=0.61803399; //黄金分割点
const double tPHI=0.38196601; template<typename T>
inline T read(T&x){
x=;int f=;char ch=getchar();
while (ch<''||ch>'') f|=(ch=='-'),ch=getchar();
while (ch>=''&&ch<='') x=x*+ch-'',ch=getchar();
return x=f?-x:x;
} /*-----------------------showtime----------------------*/
const int maxn = ;
int mp[maxn][maxn];
int mx[maxn][maxn],mn[maxn][maxn];
deque<int>qmx,qmn;
int main(){
int n,m,k;
scanf("%d%d%d", &n, &m, &k);
for(int i=; i<=n; i++){
for(int j=; j<=m; j++){
scanf("%d", &mp[i][j]);
}
} for(int i=; i<=n; i++){
qmx.clear();
qmn.clear();
for(int j=; j<=m; j++){
while(!qmx.empty() && mp[i][qmx.back()] <= mp[i][j]) qmx.pop_back();
qmx.push_back(j);
while(!qmx.empty() && j - qmx.front() + > k) qmx.pop_front();
mx[i][j] = mp[i][qmx.front()]; while(!qmn.empty() && mp[i][qmn.back()] >= mp[i][j]) qmn.pop_back();
qmn.push_back(j);
while(!qmn.empty() && j - qmn.front() + > k) qmn.pop_front();
mn[i][j] = mp[i][qmn.front()];
}
}
int ans = inf;
for(int j=; j<=m; j++){
qmx.clear();
qmn.clear();
for(int i=; i<=n; i++){
while(!qmx.empty() && mx[qmx.back()][j] <= mx[i][j]) qmx.pop_back();
qmx.push_back(i);
while(!qmx.empty() && i - qmx.front() + > k) qmx.pop_front();
int tpmx = mx[qmx.front()][j]; while(!qmn.empty() && mn[qmn.back()][j] >= mn[i][j]) qmn.pop_back();
qmn.push_back(i);
while(!qmn.empty() && i - qmn.front() + > k) qmn.pop_front();
int tpmn = mn[qmn.front()][j]; if(i>=k&&j>=k) ans = min(ans, tpmx - tpmn);
}
}
printf("%d\n", ans); return ;
}