题目链接
解题思路
容易想到动态规划,设 f i ( x , y ) f_i(x, y) fi(x,y) 表示前 i i i 步到达 ( x , y ) (x, y) (x,y) 的最大滑动次数。以 d = 1 d = 1 d=1 为例,可得方程: f i ( x , y ) = max z ∈ [ x , x + t ] { f i − 1 ( z , y ) + z − x } f_i(x, y) = \max_{z \in [x, x + t]} \{ f_{i - 1}(z, y) + z - x \} fi(x,y)=maxz∈[x,x+t]{fi−1(z,y)+z−x} 。
设 g i ( x , y ) = f i ( x , y ) + x g_i(x, y) = f_i(x, y) + x gi(x,y)=fi(x,y)+x ,则 f i ( x , y ) = max z ∈ [ x , x + t ] { g i − 1 ( z , y ) } − x f_i(x, y) = \max_{z \in [x, x + t]} \{ g_{i - 1}(z, y) \} - x fi(x,y)=maxz∈[x,x+t]{gi−1(z,y)}−x ,从大到小枚举 x x x ,则可使用单调队列优化,用 O ( 1 ) O(1) O(1) 时间复杂度计算 max z ∈ [ x , x + t ] { g i − 1 ( z , y ) } \max_{z \in [x, x + t]} \{ g_{i - 1}(z, y) \} maxz∈[x,x+t]{gi−1(z,y)} 。
具体实现时可优化掉 f f f 的 i i i 和 g g g 的 i , y i, y i,y 。比较毒瘤的是四个方向要分类讨论,我也没想到什么好方法能把它们合在一起。
代码
#define pb push_back
#define ppb pop_back
#define ppf pop_front
#include <bits/stdc++.h>
template <typename T>
constexpr T &maxeq(T &a, const T &b) { return a < b ? (a = b) : a; }
using namespace std;
template <typename... T>
using vec = vector<T...>;
using vb = vec<bool>;
using vbr = vb::reference;
using vvb = vec<vb>;
using vi = vec<int>;
using vvi = vec<vi>;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, m, x, y, k;
cin >> n >> m >> x >> y >> k;
vvb board(n, vb(m));
for (vb &i : board)
for (vbr j : i)
{
char c;
cin >> c;
j = c == 'x';
}
vvi f(n, vi(m, 0xc0c0c0c0));
f[x - 1][y - 1] = 0;
for (int s, t, d; k--;)
{
cin >> s >> t >> d;
t -= s - 1;
switch (d)
{
case 1:
for (int j{}; j < m; ++j)
{
deque<int> q;
vi g(n);
for (int i{n - 1}; i >= 0; --i)
if (board[i][j])
q.clear();
else
{
g[i] = f[i][j] + i;
while (!q.empty() && q.front() > i + t)
q.ppf();
while (!q.empty() && g[q.back()] < g[i])
q.ppb();
q.pb(i);
f[i][j] = g[q.front()] - i;
}
}
break;
case 2:
for (int j{}; j < m; ++j)
{
deque<int> q;
vi g(n);
for (int i{}; i < n; ++i)
if (board[i][j])
q.clear();
else
{
g[i] = f[i][j] - i;
while (!q.empty() && q.front() < i - t)
q.ppf();
while (!q.empty() && g[q.back()] < g[i])
q.ppb();
q.pb(i);
f[i][j] = g[q.front()] + i;
}
}
break;
case 3:
for (int i{}; i < n; ++i)
{
deque<int> q;
vi g(m);
for (int j{m - 1}; j >= 0; --j)
if (board[i][j])
q.clear();
else
{
g[j] = f[i][j] + j;
while (!q.empty() && q.front() > j + t)
q.ppf();
while (!q.empty() && g[q.back()] < g[j])
q.ppb();
q.pb(j);
f[i][j] = g[q.front()] - j;
}
}
break;
case 4:
for (int i{}; i < n; ++i)
{
deque<int> q;
vi g(m);
for (int j{}; j < m; ++j)
if (board[i][j])
q.clear();
else
{
g[j] = f[i][j] - j;
while (!q.empty() && q.front() < j - t)
q.ppf();
while (!q.empty() && g[q.back()] < g[j])
q.ppb();
q.pb(j);
f[i][j] = g[q.front()] + j;
}
}
}
}
int ans{};
for (vi &i : f)
maxeq(ans, *max_element(i.begin(), i.end()));
cout << ans << '\n';
return 0;
}