P3739 [HAOI2014]走出金字塔 题解
Asakawa_Luka · · 题解
太长不看版
设:
-
Dr. Kong 当前所在房间为
(x_1, y_1) ,出口房间为(x_2, y_2) ; -
Dr. Kong 从
(x_1, y_1) 走到(x_2, y_2) 的次数为f(x_1, y_1, x_2, y_2) ; -
令
g(x_1, y_1, x_2, y_2) = \left \{ \begin{aligned} & \lvert x_2 - x_1 + y_2 - y_1 \rvert + x_1 - x_2 \quad \lvert x_2 - x_1 + y_2 - y_1 \rvert > x_2 - x_1 \\ & y_2 \bmod 2 - y_1 \bmod 2\quad \lvert x_2 - x_1 + y_2 - y_1 \rvert \leq x_2 - x_1 \\ \end{aligned} \right .
则:
答案即:
正文
正文部分主要介绍如何推出以上函数。
由上定义,容易看出
最简单的想法是一层一层向下推进,共需走层数乘以二步,即
考虑到
对于上面这个想法,容易举出反例,如
之所以如此,是因为向下推进最左边只能到
易知无论在哪一层,无论怎么分配从
由上,在无法直接推进到
此时我们令额外走的次数为
由题得,移动一次的代价为
由于有多个出口,找到最小代价并检查是否合法,得到:
以上。
代码
// Problem: P3739 [HAOI2014]走出金字塔
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P3739
// Memory Limit: 125 MB
// Time Limit: 1000 ms
// Author: Asakawa_Luka (https://www.luogu.com.cn/user/321898)
// Powered by CP Editor (https://cpeditor.org)
#include <algorithm>
#include <iostream>
#include <limits>
namespace Solution {
constexpr std::size_t AbsMinus(const std::size_t &lhs,
const std::size_t &rhs) noexcept {
return lhs < rhs ? rhs - lhs : lhs - rhs;
}
constexpr std::size_t f(const std::size_t &x1, const std::size_t &y1,
const std::size_t &x2, const std::size_t &y2) noexcept {
return x1 <= x2 ? ((x2 - x1) << 1u) +
(AbsMinus(x2 + y1, x1 + y2) <= x2 - x1
? (y2 & 1u) - (y1 & 1u)
: AbsMinus(x2 + y1, x1 + y2) - (x2 - x1))
: f(x2, y2, x1, y1);
}
int main() noexcept {
std::size_t n, m, k, s, xa, ya, res = std::numeric_limits<std::size_t>::max();
std::cin >> n >> m >> k >> s >> xa >> ya;
for (std::size_t x, y; m; --m) {
std::cin >> x >> y;
res = std::min(res, f(xa, ya, x, y));
}
if (const std::size_t &c = res * k; c < s)
std::cout << s - c - 1u;
else
std::cout << "-1";
return 0;
}
} // namespace Solution
int main() noexcept {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return Solution::main();
}