10182. 「一本通 5.5 练习 3」理想的正方形

2022-09-19 12:18:51 浏览数 (1)

10182. 「一本通 5.5 练习 3」理想的正方形

题意

有一个 atimes b 的整数组成的矩阵,现请你从中找出一个 ntimes n 的正方形区域,使得该区域所有数中的最大值和最小值的差最小。

思路

肯定会TLE。 考虑优化。 发现该式子很像RMQ。于是可得:

dp[i][j][k]=max(dp[i][j][k], dp[i 2^(k-1)][j 2^(k-1)][k-1],dp[i,j 2^(k-1)][k-1], dp[i 2^(k-1)][j][k-1])
代码语言:javascript复制
#include<algorithm>
#include<bitset>
#include<complex>
#include<deque>
#include<exception>
#include<fstream>
#include<functional>
#include<iomanip>
#include<ios>
#include<iosfwd>
#include<iostream>
#include<istream>
#include<iterator>
#include<limits>
#include<list>
#include<locale>
#include<map>
#include<memory>
#include<new>
#include<numeric>
#include<ostream>
#include<queue>
#include<set>
#include<sstream>
#include<stack>
#include<stdexcept>
#include<streambuf>
#include<string>
#include<typeinfo>
#include<utility>
#include<valarray>
#include<vector>
#include<cctype>
#include<cerrno>
#include<cfloat>
#include<ciso646>
#include<climits>
#include<clocale>
#include<cmath>
#include<csetjmp>
#include<csignal>
#include<cstdarg>
#include<cstddef>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#define int long long
using namespace std;
inline int read(){
    int res=0,f=1;char ch=getchar();
    while(ch<'0'ch>'9'){if(ch=='-') f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') res=res*10 ch-'0',ch=getchar();
    return res*f;
}
inline void write(int x){
    if(x<0) putchar('-'),x=-x;
    if(x<10) putchar(x '0');
    else{
        write(x/10);
        putchar(x '0');
    }
}
//queue<int> q;
//set<int> s;
//priority_queue<int> q1;
//priority_queue<int,vector<int>,greater<int> > q2;
//list<int> l;
//stack<int> s;
int a,b,n,g[1010][1010],ans=2e18,logn=20;
int dp[1500][1500];
int dp1[1500][1500];
void st(){
    for(int k=0;k<logn;k  ){
        for(int i=0;i (1<<k)<a;i  ){
            for(int j=0;j (1<<k)<b;j  ){
                dp[i][j]=max(dp[i][j],max(dp[i (1<<k)][j (1<<k)],max(dp[i (1<<k)][j],dp[i][j (1<<k)])));
                dp1[i][j]=min(dp1[i][j],min(dp1[i (1<<k)][j (1<<k)],min(dp1[i (1<<k)][j],dp1[i][j (1<<k)])));
            }
        }
    }
}
signed main(){
    a=read();b=read();n=read();
    for(register int i=0;i<a;i  ){
        for(register int j=0;j<b;j  ) dp[i][j]=dp1[i][j]=g[i][j]=read();
    }
    logn=log2(n);
    st();
    for(register int i=0;i<=a-n;i  ){
        for(register int j=0;j<=b-n;j  ){
            int Max=0,Min=0;
            Max=max(dp[i][j],max(dp[i n-(1<<logn)][j n-(1<<logn)],max(dp[i n-(1<<logn)][j], dp[i][j n-(1<<logn)])));
            Min=min(dp1[i][j],min(dp1[i n-(1<<logn)][j n-(1<<logn)],min(dp1[i n-(1<<logn)][j], dp1[i][j n-(1<<logn)])));
            ans=min(ans,Max-Min);
        }
    }
    write(ans);putchar('n');
    return 0;
}

后记

理论上这道题用二维线段树、二维RMQ都是可以的。 结果我全炸了。。。

mq

0 人点赞