这道题 P2716 和谐的雪花 本质和 P2216 [HAOI2007] 理想的正方形 是一模一样的,评蓝有点高了。
本题解解法为单调对列。当然,看题目,是可以使用 ST 表或者线段树之类的做。中心思想就是用单调队列维护固定区间内最大最小值,加上二分答案。
根据题意,很容易想象到二分 \(n\) 的取值,剩下的就是用单调队列,正常单调一个矩阵是不能的,但是可以用两次单调队列,把一个矩阵的最值,压到矩阵的最右下角,然后求解即可。
说的有点多了。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
const int N = 510, M = N * N;
int g[N][N];
int n, m, k;
int dx[N][N], dy[N][N];
int tx[N][N], ty[N][N];
int q[N];
bool check(int x)
{
for (int i = 1; i <= n; i ++ )
{
auto &a = g[i];
int hh = 0, tt = -1;
for (int j = 1; j <= m; j ++ )
{
if (hh <= tt && q[hh] <= j - x) hh ++ ;
while (hh <= tt && a[q[tt]] <= a[j]) tt -- ;
q[ ++ tt] = j;
if (j >= x) dx[j][i] = a[q[hh]];
}
}
for (int i = x; i <= m; i ++ )
{
auto &a = dx[i];
int hh = 0, tt = -1;
for (int j = 1; j <= n; j ++ )
{
if (hh <= tt && q[hh] <= j - x) hh ++ ;
while (hh <= tt && a[q[tt]] <= a[j]) tt -- ;
q[ ++ tt] = j;
if (j >= x) dy[j][i] = a[q[hh]];
}
}
for (int i = 1; i <= n; i ++ )
{
auto &a = g[i];
int hh = 0, tt = -1;
for (int j = 1; j <= m; j ++ )
{
if (hh <= tt && q[hh] <= j - x) hh ++ ;
while (hh <= tt && a[q[tt]] >= a[j]) tt -- ;
q[ ++ tt] = j;
if (j >= x) tx[j][i] = a[q[hh]];
}
}
for (int i = x; i <= m; i ++ )
{
auto &a = tx[i];
int hh = 0, tt = -1;
for (int j = 1; j <= n; j ++ )
{
if (hh <= tt && q[hh] <= j - x) hh ++ ;
while (hh <= tt && a[q[tt]] >= a[j]) tt -- ;
q[ ++ tt] = j;
if (j >= x) ty[j][i] = a[q[hh]];
}
}
int maxv = -0x3f3f3f3f;
for (int i = x; i <= n; i ++ )
{
for (int j = x; j <= m; j ++ )
{
maxv = max(maxv, dy[i][j] - ty[i][j]);
// cout << ty[i][j] << ' ';
}
// puts("");
}
return maxv >= k;
}
int main()
{
cin >> n >> m >> k;
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
scanf("%d", &g[i][j]);
int l = 1, r = min(n, m) + 1;
while (l < r)
{
int mid = l + r >> 1;
if (check(mid)) r = mid;
else l = mid + 1;
}
if (r == min(n, m) + 1) puts("-1");
else cout << r << endl;
return 0;
}
标签:int,tt,雪花,mid,hh,P2716,和谐,include,单调
From: https://www.cnblogs.com/blind5883/p/18234716