[Bzoj1047][HAOI2007]理想的正方形(ST表)
作者:互联网
题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=1047
题目虽然有一个n的限制,但求二维区间最值首先想到的还是RMQ,但是如果按照往常RMQ的写法,空间复杂度是O(n2*(log2(n)2)),而且需要两个求最大最小,所以会爆空间,大概也会T,233。
所以这个时候发现n还是蛮重要的,dp[i][j]表示以点(i,j)为左上角,(i+(1<<(log2(n)-1)),j+(1<<(log2(n)-1)))为右下角的矩形区域内的最值。
如果不好理解可以在开一维k,即dp[i][j][k]表示以点(i,j)为左上角,(i+(1<<(k-1)),j+(1<<(k-1)))为右下角的矩形区域最值。
这样预处理之后枚举左上角,可以做到O(1)查询区间最值。
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const int maxn = 1010; 5 const int inf = 2e9; 6 int dpM[maxn][maxn]; 7 int dpm[maxn][maxn]; 8 int logk; 9 int query(int x, int y, int k) { 10 int w = k - (1 << logk); 11 int Max = max(max(dpM[x][y], dpM[x + w][y + w]), max(dpM[x + w][y], dpM[x][y + w])); 12 int Min = min(min(dpm[x][y], dpm[x + w][y + w]), min(dpm[x + w][y], dpm[x][y + w])); 13 return Max - Min; 14 } 15 int main() { 16 int n, m, k, x; 17 scanf("%d%d%d", &n, &m, &k); 18 for (int i = 1; i <= n; ++i) 19 for (int j = 1; j <= m; ++j) { 20 scanf("%d", &x); 21 dpM[i][j] = dpm[i][j] = x; 22 } 23 logk = log2(k); 24 for (int t = 0; t < logk; t++) { 25 for (int i = 1; i + (1 << t) <= n; i++) { 26 for (int j = 1; j + (1 << t) <= m; j++) { 27 dpM[i][j] = max(max(dpM[i][j], dpM[i + (1 << t)][j + (1 << t)]), max(dpM[i + (1 << t)][j], dpM[i][j + (1 << t)])); 28 dpm[i][j] = min(min(dpm[i][j], dpm[i + (1 << t)][j + (1 << t)]), min(dpm[i + (1 << t)][j], dpm[i][j + (1 << t)])); 29 } 30 } 31 } 32 int ans = inf; 33 for (int i = 1; i <= n - k+1; i++) { 34 for (int j = 1; j <= m - k+1; j++) { 35 ans = min(ans, query(i, j, k)); 36 //cout << query(i, j, k) << " "; 37 } 38 } 39 printf("%d\n", ans); 40 }
标签:RMQ,int,long,ST,HAOI2007,Bzoj1047,maxn,左上角,最值 来源: https://www.cnblogs.com/sainsist/p/11147611.html